Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing only specific match's group using Java regular expressions by (new Matcher..).replaceAll

Good day to all!
Using (Java) regular expressions, I’m trying to execute [Matcher] replaceAll to replace only a specific group, not all matches. Can you tell me how to do it in JAVA? Thank you very much in advance!

static void main(String[] args) {
        String exp = "foofoobarfoo";
    
        exp = Pattern
                .compile("foo(foo)")
                .matcher(exp)
                .replaceAll(gr -> "911" + gr.group(1) + "911");

        
        System.out.println(exp);        
    }

expecting : foo911foo911barfoo

actually
resulted : 911foo911barfoo
(Because replaceAll applied the replacement string to all matches, namely the groups gr.group(0) (foo foo bar foo) and gr.group(1) (foo bar foo). And it is necessary to replace only gr.group(1), without gr.group(0)).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to select a specific group to replace in a string from a regular expression.

Please tell me how it is done correctly. Thank a lot in advance!

>Solution :

You need to capture the first foo, too:

exp = Pattern
                .compile("(foo)(foo)")
                .matcher(exp)
                .replaceAll(gr -> gr.group(1) + "911" + gr.group(2) + "911");

See the Java demo online.

Since there are two capturing groups now – (foo)(foo) – there are now two gr.group()s in the replacement: gr.group(1) + "911" + gr.group(2) + "911".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading