user167908
user167908

Reputation: 977

.Net Regex match for a browser agent version?

Looking for a browser agent regex to match the OS version, I have the following as test cases:

Apple~iPad~iOS~7~Mobile Safari~7.0"); << should match
Apple~iPad~iOS~7.12~Mobile Safari~7.0"); << should match
Apple~iPad~iOS~7.12.45~Mobile Safari~7.0"); << should match
Apple~iPad~iOS~7.99.451.987~Mobile Safari~7.0") << should match
Apple~iPad~iOS~blah~Mobile Safari~7.0"); << should NOT match
Apple~iPad~iOS~~Mobile Safari~7.0"); << should NOT match
Apple~iPad~iOS~7.XXXX~Mobile Safari~7.0"); << should NOT match

This gets me in the vicinity, but the last ones comes through as match on iOS~7 when it shouldn't:

iOS~(\d+)(\.\d+)?(\.\d+)?(\.\d+)?

What is the correct regex for matching desired results here?

Thanks!

Upvotes: 0

Views: 66

Answers (3)

Dalorzo
Dalorzo

Reputation: 20014

How about negative look ahead of (?!\.X) like : iOS~(\d+)(?!\.X)(\.\d+)?(\.\d+)?(\.\d+)?

Online Demo

Or you could use (?!\.\D) to match anything that is not a number

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

You could use a negative lookahead,

iOS~(\d+)(?:(\.\d+)+)?(?!\.)

DEMO

If you want to capture the numbers in groups, then use this

iOS~(\d+)(\.\d+)?(\.\d+)?(\.\d+)?(?!\.)

DEMO

OR

You could use a positive lookahead also,

iOS~(\d+)(\.\d+)?(\.\d+)?(\.\d+)?(?=~)

DEMO

Upvotes: 1

OnlineCop
OnlineCop

Reputation: 4069

Throw a (?!\.\D) in there:

iOS~(\d+)(?!\.\D)(\.\d+)?(\.\d+)?(\.\d+)?

regex101 example

Upvotes: 1

Related Questions