Pattern Matcher and replaceAll
472798May 19 2008 — edited May 26 2008Hi,<p>
I have a program that takes a longString, searches it for instances of a searchTerm and then replaces the match with a formatted version of the match (for highlighting in results page). It works, however, if the search term from the user is "java" and the found term within longString is "Java" then the returned highlighted string ends up being "<b>java</b>" when I need to preserve the true case of the letters, just need to format the word. <p>
I've searched and searched for a way to do this, but seem only to be able to do the case_insensitive search, not case_insensitive replace. Any ideas? Here's a snippet of the code:<p>
...
String phrase = foundPhrases.get(m);<p>
Pattern firstMatchedPattern = Pattern.compile(phrase, Pattern.CASE_INSENSITIVE);<p>
Matcher matchedPhrase = firstMatchedPattern.matcher(highlighted);<p>
while (matchedPhrase.find() == true) {<p>
String origPhrase = origPhrases.get(m);<p>
phrasePos = highlighted.toLowerCase().indexOf(origPhrase.toLowerCase());<p>
phraseLen = origPhrase.length(); // do not count any backslashes<p>
String thisPhrase = highlighted.substring(phrasePos, (phrasePos + phraseLen));<p>
StringBuffer hilitebuffer = new StringBuffer(CoreServices.highlightTagStart);<p>
hilitebuffer.append(thisPhrase);<p>
hilitebuffer.append(CoreServices.highlightTagEnd);<p>
String hilitePhrase = hilitebuffer.toString();<p>
//highlighted = matchedPhrase.replaceAll(hilitePhrase);<p>
highlighted = highlighted.replace(thisPhrase, hilitePhrase);<p>
}<p>
...<p>
Thanks,
Ginni
Message was edited by:
ginnim