Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Regex Replacement in Java

Tags:

java

regex

I want to find all patterns in a string that match the regex: no="(\d+)" then replace the digits in the group with something else.

In the method below I can find and replace the entire match, but that is not what I want. Is there a way to replace just a portion in that match?

private String replaceStringFromPatternSearch(String stringToSearch, String patternString, String replacementString) {
    String replacedString = null;
    Pattern stringPattern = Pattern.compile(patternString);

    Matcher stringMatcher = stringPattern.matcher(stringToSearch);
    replacedString = stringMatcher.replaceAll(replacementString);
    if (replacedString != null) {
        return replacedString;
    } else {
        return stringToSearch;
    }
}
like image 422
Phillip Gibb Avatar asked Jul 31 '14 07:07

Phillip Gibb


People also ask

How do you replace a character in a string in Java regex?

Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.


2 Answers

No Callbacks / Lambdas in Java Replace, But We Have Other Options

Option 1: Use Capture Buffers in Replacement Function

In replaceAll, you can build your replacement from components such as captured text and strings you want to insert at that time. Here is an example:

String replaced = yourString.replaceAll("no=\"(\\d+)\"", 
                                         "Something $1 Something else");

In the replacement, $1 are the captured digits. You don't have to use them, but as you can see you can build a replacement string around them.

Option 2 (Replacement Lambda/Callback/Delegate Equivalent): Build it One Match At a Time

In Java, to build even more sophisticated replacement, we don't have replacement lambdas, but we can do this:

StringBuffer resultString = new StringBuffer();
Pattern regex = Pattern.compile("no=\"(\\d+)\"");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
        // You can vary the replacement text for each match on-the-fly
        // String computed_replacement = .... Something wild!
        regexMatcher.appendReplacement(resultString, computed_replacement );
    } 
regexMatcher.appendTail(resultString);
like image 80
zx81 Avatar answered Sep 28 '22 20:09

zx81


You could use lookarounds, so that the matches will only be the digits:

(?<=no=")\d+(?=")

Regular expression visualization

Debuggex Demo

like image 30
sp00m Avatar answered Sep 28 '22 21:09

sp00m