Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a regular expression with another regex

Tags:

java

regex

I want to replace some regex with regex in java for e.g.

Requirement:

Input: xyxyxyP

Required Output : xyzxyzxyzP

means I want to replace "(for)+\{" to "(for\{)+\{" . Is there any way to do this?

I have tried the following code

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class ReplaceDemo2 {

    private static String REGEX = "(xy)+P";
    private static String INPUT = "xyxyxyP";
    private static String REGEXREPLACE = "(xyz)+P";

    public static void main(String[] args) {
        Pattern p = Pattern.compile(REGEX);
        // get a matcher object
        Matcher m = p.matcher(INPUT);
        INPUT = m.replaceAll(REGEXREPLACE);
        System.out.println(INPUT);
    }
}

but the output is (xyz)+P .

like image 766
Monti Chandra Avatar asked Sep 13 '26 09:09

Monti Chandra


1 Answers

You can achieve it with a \G based regex:

String s = "xyxyxyP";
String pattern = "(?:(?=xy)|(?!^)\\G)xy(?=(?:xy)*P)";
System.out.println(s.replaceAll(pattern, "$0z")); 

See a regex demo and an IDEONE demo.

In short, the regex matches:

  • (?:(?=xy)|(?!^)\\G) - either a location followed with xy ((?=xy)) or the location after the previous successful match ((?!^)\\G)
  • xy - a sequence of literal characters xy but only if followed with...
  • (?=(?:xy)*P) - zero or more sequences of xy (due to (?:xy)*) followed with a P.
like image 154
Wiktor Stribiżew Avatar answered Sep 14 '26 23:09

Wiktor Stribiżew