Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

change a part of file via regex and java

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

Upvotes: 1

Views: 39

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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)
                            ^^

Upvotes: 1

Related Questions