Home
News
Feed
search engine
by
freefind
advanced
How to find and replace regular expressions with groups in java
2015-01-13
azim58 - How to find and replace regular expressions with groups in java Pattern patt = Pattern.compile("(F)ourth"); Matcher m = patt.matcher(text); StringBuffer sb = new StringBuffer(text.length()); while (m.find()) { String text2 = m.group(1); // ... possibly process 'text' ... m.appendReplacement(sb, Matcher.quoteReplacement(text2)); } m.appendTail(sb); System.out.println(sb.toString()); =========================================================================== I'll just turn this into a function and put it into my useful tools public String findAndReplacewithRegEx(String text, String find, String replace) { Pattern patt = Pattern.compile(find); Matcher m = patt.matcher(text); StringBuffer sb = new StringBuffer(text.length()); while (m.find()) { m.appendReplacement(sb, replace); } m.appendTail(sb); return sb.toString(); }
azim58wiki: