Reputation: 5189
I've been having problems extracting the value of a Regex in a String. I have a string with several regex expressions and I need to get the value of each expression's match. The thing is though, it's not returning the last match correctly. For example:
Regex Pattern: I play (\S+.*?) and (\S+.*?)
String: I play the guitar and the bass
The program is returning the value of the first expression as "the guitar" but it's returning the value of the second expression as "the" instead of "the bass". Is there a way to fix this?
Upvotes: 0
Views: 94
Reputation: 78185
Well, you ask for a match with a minimum length using the .*?
, so there you go.
It works fine for the first group becase and
is an anchor. For the second group, there's no anchor, thus the minimum match.
Try adding the end of string marker as an anchor: I play (\S+.*?) and (\S+.*?)$
Upvotes: 1