从服务器端获取字符串,并在Kotlin中从字符串中分离代码片段



我制作了一个Android应用程序,用户可以在其中提问,但他们可能会在提问中使用编程代码。如何将编程代码与Kotlin中的正常文本分离?如果你能解释的话,我想改变代码的背景。像这样在此处输入图像描述

只需使用类似stackerflow的东西,即将代码放在"```"您可以很容易地从字符串中解析它。

更多信息:要解析字符串,可以使用Regex

这里有一些样本代码```"并将内部文本更改为红色:

...
onCreate(){
textView.setText(formatString("alo ```alo```"));
}
...
SpannableStringBuilder formatString(String message) {
Pattern p = Pattern.compile("(```)(.*?)(```)");// detects the pattern ```*``` in the string
Matcher matcher = p.matcher(message);
SpannableStringBuilder spannable = new SpannableStringBuilder(message);
//for changing color of text
while (matcher.find()) {
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.replace(spannable.getSpanStart(span), spannable.getSpanStart(span) + 3, "");
spannable.replace(spannable.getSpanEnd(span) - 3, spannable.getSpanEnd(span), ""); //to remove ``` from string
}
return spannable;
}

最新更新