1

This piece of code

String Str = new String("${project_loc:A}/Foo.yaml;${project_loc:B}/Bar.yaml");
System.out.println(Str.replaceFirst("[$][{].*[}]/", ""));

prints

Bar.yaml

while what I am trying to achieve is:

Foo.yaml;${project_loc:B}/Bar.yaml

Why is it stopping at second closing braces i.e. }, not at first?

What regex exp can be passed to replaceFirst() to achieve the desired result?

FYI: I tried few things at https://regex101.com/ but couldn't find any success.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • 1
    Use `\\$\\{.[^}]*}/` for your search regex as `.*` is greedy – anubhava Jan 25 '18 at 10:55
  • 2
    use this : System.out.println(Str.replaceFirst("[$][{].*?[}]/", "")); . The additional ? makes the expression non-greedy. Else by default regex patterns are greedy matches – akshaya pandey Jan 25 '18 at 10:58

1 Answers1

3

Dot-asterisk .* will consume everything, including as many }s as it can find; use [^}]* to stop at the first } instead:

System.out.println(Str.replaceFirst("[$][{][^}]*[}]/", ""));

Demo 1.

You could also use reluctant quantifier .*?:

System.out.println(Str.replaceFirst("[$][{].*?[}]/", ""));

Demo 2.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523