仅从相似的单词组中点亮一个单词

问题描述 投票:0回答:1

我想一次仅突出显示一个单词。

这里是代码

String newString = joker[j].replaceAll(utteranceId, "<span style= 'background-color:green'>" + utteranceId + "</span>");
 textSent.setText(Html.fromHtml(newString));

Here the word "of" is got highlighted in multiple places

我只想一次突出显示一个单词“ of”。如果有一个句子在很多地方都存在相同的单词我只想突出显示一个单词

java android-studio highlight
1个回答
0
投票

String类也具有方法replaceFirstreplaceFirstreplaceAll都有一个正则表达式作为第一个参数。因此,可能需要用引号引起来。

String str = "test - test - test";
String result = str.replaceFirst(Pattern.quote("test"), "<span style= 'background-color:green'>$0</span>");
System.out.println(result);

结果:

<span style= 'background-color:green'>test</span> - test - test

要替换第二,第三或最后一场比赛,请使用以下方法:

String str = "test - test - test";
Pattern pattern = Pattern.compile(Pattern.quote("test"));
Matcher matcher = pattern.matcher(str);
int i = 0;
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
  if (i == 1) { // index of the match: 0, 1, 2 etc.
    String value = matcher.group();
    matcher.appendReplacement(sb, "<span style= 'background-color:green'>" + value + "</span>");
  }
  i++;
}
matcher.appendTail(sb);
System.out.println(sb.toString());

结果是:

test - <span style= 'background-color:green'>test</span> - test
© www.soinside.com 2019 - 2024. All rights reserved.