Last active
February 11, 2022 16:01
-
-
Save nickrussler/42f8619f1a36eea25364 to your computer and use it in GitHub Desktop.
String replace with callback in Java (like in JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class Example { | |
public static void main(String[] args) { | |
String result = StringReplacer.replace("Hello World!", Pattern.compile("\\d+"), m -> ("" + (Integer.parseInt(m.group()) * 2)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class StringReplacer { | |
public static String replace(String input, Pattern regex, Function<Matcher, String> callback) { | |
StringBuffer resultString = new StringBuffer(); | |
Matcher regexMatcher = regex.matcher(input); | |
while (regexMatcher.find()) { | |
regexMatcher.appendReplacement(resultString, callback.apply(regexMatcher)); | |
} | |
regexMatcher.appendTail(resultString); | |
return resultString.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gorodkovdmitriy это зарубежный сайт, твои благодарности все-равно не поймут.