简体   繁体   中英

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.

"[^"]*"

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM