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;
    }
}
                Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
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);
                        You could use lookarounds, so that the matches will only be the digits:
(?<=no=")\d+(?=")

Debuggex Demo
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