Reputation: 17654
Imagine I have the String
abcD
and I want to extract abc
out of it. I thought of using
^(.+)D$
however then in matching group1, not only abc
, but abcD
is included - how to make the .+
less greedy, so D
is not included in the group? I know I could use [^D]+
, but is this really the only way?
Sorry, this was a reduced an bad test-case. Have a look at this sample (Java):
Pattern pattern = Pattern.compile("^(\\{(.+?)\\})?$");
Matcher matcher = pattern.matcher("{a}{b}");
System.out.println(matcher.matches()); // true
Why does this match? Shouldn't the regular expression just allow one {
and one }
in the String in total? I want only things like {< not } >}
to match.
Upvotes: 0
Views: 165
Reputation: 2032
"D" is not included in the first group, it is included in the full pattern match.
The first group is "abc".
You can see a demo of this at http://rubular.com/r/oSnF17Jd39
Upvotes: 0
Reputation: 3039
To make a quantifier less greedy, you add a ?
after the quantifier:
^(.+?)D$
This depends, though, on your language or text editor. Different regex engines support different functionalities.
Upvotes: 2