I'm trying to do something like this:
public String evaluateString(String s){
Pattern p = Pattern.compile("someregex");
Matcher m = p.matcher(s);
while(m.find()){
m.replaceCurrent(methodFoo(m.group()));
}
}
The problem is that there is no replaceCurrent method. Maybe there is an equivalent I overlooked. Basically I want to replace each match with the return value of a method called on that match. Any tips would be much appreciated!
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .
The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.
Since Java 9 we can use Matcher#replaceAll(Function<MatchResult,String> replacer)
like
String result = Pattern.compile("yourRegex")
.matcher(yourString)
.replaceAll(match -> yourMethod(match.group()));
// ^^^- or generate replacement directly
// like `match.group().toUpperCase()`
Before Java 9
You may use Matcher#appendReplacement
and Matcher#appendTail
.
appendReplacement
will do two things:
appendTail
will add to buffer text placed after current match.
Pattern p = Pattern.compile("yourRegex");
Matcher m = p.matcher(yourString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, yourMethod(m.group()));
}
m.appendTail(sb);
String result = sb.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With