1

I have 2 different results betwin regex online and my java code.

My input text:

Examples:
    #DATA
    |id|author|zip|city|element|
    Odl data - Odl data - Odl data    
    #END

I want change Odl data - Odl data - Odl data (in my example) by foo.

My regex is:

#DATA[\s\S].*[\s\S]([\s\S]*)#END

I want change Group 1 by foo

enter image description here

démo online:

https://regex101.com/r/Nq9fas/2

My java code:

final String regex = "#DATA[\\s\\S].*[\\s\\S]([\\s\\S]*)#END";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

if (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

I want keep the 1st line (|id|author|zip|city|element|) but my regex change all data betwin #DATA and #END

1

1 Answer 1

1

The point is to match what you need to remove/replace and match and capture what you need to keep.

You may use a replaceFirst with

(#DATA\r?\n.*\r?\n)[\s\S]*(#END)

See the regex demo. In Java:

String res = s.replaceFirst("(#DATA\r?\n.*\r?\n)[\\s\\S]*(#END)", "$1foo\n$2");

Note: If you have only one 1 line to replace, use

(#DATA\r?\n.*\r?\n).*([\s\S]*#END)

Note 2: If you have several such "blocks" in the text, use a lazy quantifier with [\s\S] and use with replaceAll instead of replaceFirst:

(#DATA\r?\n.*\r?\n).*([\s\S]*?#END)
                            ^^
Sign up to request clarification or add additional context in comments.

Comments

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.