Icemanind
Icemanind

Reputation: 48696

RegEx Pattern to match a string

I am looking for a regex pattern that will match a string. A string, defined as anything in quotes. What I'm trying to do is parse these strings:

PRINT "test"
PRINT "Hello":PRINT "World"

The pattern I have now is: "\".*\"". It parses the first line fine. It returns /"test"/, but the second line, it returns /"Hello":PRINT "World"/ which is incorrect. It needs to match what's between the first quote and the second quote. It appears to be matching whatever is between the first quote and the last quote in the entire line.

Any help would be appreciated. If it matters, this is .NET Regex.

Upvotes: 1

Views: 251

Answers (2)

Tomalak
Tomalak

Reputation: 338248

"[^"]*"

The .* is greedy. It matches right to the end of the string, because nothing tells it to stop at any inbetween ". The [^"]* is greedy, too - but not as arbitrary.

Alternatively use non-greedy matching

".*?"

Also see the MSDN on Quantifiers.

Upvotes: 5

John Weldon
John Weldon

Reputation: 40769

Your problem is that regular expressions are greedy by default, meaning they'll pick up the longest matching string they can.. A non greedy version of your regex would be:

"\"[^"]+?\"

I used + instead of * assuming you'd only want to match non-empty strings.

Upvotes: 2

Related Questions