3

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 .

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please share regx of getting "xyzabzxyzP" from "xyabxyP"?
No idea what the pattern can be. Try .replaceAll("xy|(?!P)[^x]*(?:x(?!y)[^x]*)*(?=.*P)", "$0z").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.