正则表达式中的$ 1在Java中返回空

时间:2018-02-16 15:59:06

标签: java regex

我有以下Java代码

Pattern p = Pattern.compile(KeyWordsRegExp);
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "<span class=\"colorForKeyword\">$1</span>");
}
m.appendTail(sb);

我正在尝试在字符串中查找关键字并将其替换为某些HTML标记。我想

public void test{} 

返回

<span class="colorForKeyword">public</span> <span class="colorForKeyword">void</span> test{}

我上面的java代码找到了单词,但$ 1表达式没有替换找到的模式,所以我得到了

<span class="colorForKeyword"></span> <span class="colorForKeyword"></span> test{}

编辑: KeyWordRegExp是

private String KeyWordsRegExp = "(\\babstract\\b)|(\\bcontinue\\b)|(\\bfor\\b)|(\\bnew\\b)|(\\bswitch\\b)|(\\bassert\\b)|(\\bdefault\\b)|(\\bgoto\\b)|(\\bpackage\\b)|(\\bsynchronized\\b)|(\\bboolean\\b)|(\\bdo\\b)|(\\bif\\b)|(\\bprivate\\b)|(\\bthis\\b)|(\\bbreak\\b)|(\\bdouble\\b)|(\\bimplements\\b)|(\\bprotected\\b)|(\\bthrow\\b) |(\\bbyte\\b)|(\\belse\\b)|(\\bimport\\b)|(\\bpublic\\b)|(\\bthrows\\b)|(\\bcase\\b)|(\\benum\\b)|(\\binstanceof\\b)|(\\breturn\\b)|(\\btransient\\b)|(\\bcatch\\b)|(\\bextends\\b)|(\\bint\\b)|(\\bshort\\b)|(\\btry\\b)|(\\bchar\\b)|(\\bfinal\\b)|(\\binterface\\b)|(\\bstatic\\b)|(\\bvoid\\b) |(\\bclass\\b)|(\\bfinally\\b)|(\\blong\\b)|(\\bstrictfp\\b)|(\\bvolatile\\b)|(\\bconst\\b)|(\\bfloat\\b)|(\\bnative\\b)|(\\bsuper\\b)|(\\bwhile\\b)";

str是我模式匹配的对象,因此在我提供的“public void test {}

示例中

1 个答案:

答案 0 :(得分:2)

Pattern p = Pattern.compile("(" + KeyWordsRegExp + ")");
String span = "<span class=\"colorForKeyword\">$1</span>";
str = p.matcher(str).replaceAll(span);

Pattern p = Pattern.compile(KeyWordsRegExp);
String span = "<span class=\"colorForKeyword\">$0</span>";
str = p.matcher(str).replaceAll(span);

(其中$ 0是整场比赛)

或没有图案。