Henk
Henk

Reputation: 51

Regex does not match

I need to catch the country. This is an example of the message

field1="text" field2="123.456" country="Netherlands" fieldx="text" country="United States" fieldy="more text"

When using this regex, It only matches Netherlands. It should match both countries

^.+\scountry=\"(\S+)\"

Any ideas?

Upvotes: 0

Views: 59

Answers (2)

hwnd
hwnd

Reputation: 70722

The second country you want to match includes whitespace so it fails to match, \S matches any non-whitespace character. You can use a negated character class [^ ] here instead.

country="([^"]*)"

Upvotes: 1

arshajii
arshajii

Reputation: 129477

The string United States contains a space, but in your capturing group you have \S+, which matches a string of anything but spaces.

I would suggest using [^\"]+ (i.e. a string of anything but quotes) instead:

country=\"([^\"]+)\"

(demo)

Upvotes: 1

Related Questions