我想用(*)包围时将文本变为粗体,而将(〜)包围时将其删除。我遵循此link,然后将代码修改为这样
text = "*~TEST~* *TEST* ~TEST~ TEST";
texview.setText(createSpannable(text))
private static SpannableStringBuilder createSpannable(final String str) {
StringBuffer stringBuffer = new StringBuffer();
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
//Matcher matcher = BOLD_REGEX.matcher(str);
Matcher matcher = Pattern.compile("(\\*(.*?)\\*)|(~(.*?)~)").matcher(str); //BOLD | STRIKE
while (matcher.find()) {
String group = matcher.group();
stringBuffer.setLength(0);
if (BOLD_REGEX.matcher(group).matches()) {//(\*(.*?)\*)
String spanText = group.substring(1, group.length() - 1);
matcher.appendReplacement(stringBuffer, spanText);
spannableStringBuilder.append(stringBuffer.toString());
int start = spannableStringBuilder.length() - spanText.length();
spannableStringBuilder.setSpan(new StyleSpan(BOLD), start, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (STRIKE_REGEX.matcher(spannableStringBuilder).matches()) {
createSpannable(spannableStringBuilder.toString());
}
}
if (STRIKE_REGEX.matcher(group).matches()) {//(~(.*?)~)
String spanText1 = group.substring(1, group.length() - 1);
matcher.appendReplacement(stringBuffer, spanText1);
spannableStringBuilder.append(stringBuffer.toString());
int start1 = spannableStringBuilder.length() - spanText1.length();
spannableStringBuilder.setSpan(new StrikethroughSpan(), start1, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (BOLD_REGEX.matcher(spannableStringBuilder).matches()) {
createSpannable(spannableStringBuilder.toString());
}
}
}
stringBuffer.setLength(0);
matcher.appendTail(stringBuffer);
spannableStringBuilder.append(stringBuffer.toString());
return spannableStringBuilder;
}
期望输出:
我的输出:
我该如何实现?