I have the following Java code
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);
I am trying to locate keywords in a string and replace them with some HTML markup. I would like
public void test{}
to return as
<span class="colorForKeyword">public</span> <span class="colorForKeyword">void</span> test{}
The java code I have above locates the words fine but the $1 expression is not replacing the found pattern so I get
<span class="colorForKeyword"></span> <span class="colorForKeyword"></span> test{}
edit: KeyWordRegExp is
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 is what I am pattern matching against, thus in the example I provide "public void test{}
Pattern p = Pattern.compile("(" + KeyWordsRegExp + ")");
String span = "<span class=\"colorForKeyword\">$1</span>";
str = p.matcher(str).replaceAll(span);
or
Pattern p = Pattern.compile(KeyWordsRegExp);
String span = "<span class=\"colorForKeyword\">$0</span>";
str = p.matcher(str).replaceAll(span);
(where $0 is the entire match)
or without Pattern.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments