tags:

views:

41

answers:

2

I am trying in Java to surround a word in HTML with some markup. This code throws a ArrayIndexOutOfBoundsException when the replaceAll is called.

Pattern pattern = Pattern.compile(wordToHighlight + "\\w{0,5}");
String replacement = "<span class='highlight'>$1</span>";
Matcher matcher = pattern.matcher(html);

if (matcher != null)
    if (matcher.find())
        retVal = matcher.replaceAll(replacement);
+4  A: 

I'm not familiar with Regex in Java so I'll just go ahead and make a guess, excuse me if I'm way off base. In PCRE (PHP) $1 would refer to the first capture group, since you don't have a capture group that could throw an error. Try using $0.

Cags
+1  A: 

You should try putting a capturing group on your search expression. i.e. wrap your string in parentheses.

i.e.

"(" + wordToHighlight + "\\w{0,5})"
Carl Smotricz