Digital-Clouds
Digital-Clouds

Reputation: 552

Regex returns a match in Javascript, but not C#

I have a RegEx that I'm using to get the version number from iOS user agent strings.

My RegEx is /OS ([0-9_]+)/g, and it's being applied to a user agent string like Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53

I've tested this on an online RegEx tool, and it claims it should work as I intend. My test is here. I've tried it in Javascript, and I get a match. I've then put it into C#, and I don't get a match. I'm using Regex.Match(...):

string uaString = @"Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53";

bool matched = Regex.IsMatch(uaString, @"/(?:OS )([0-9_]+)/g"); // is false

Match match = Regex.Match(uaString, @"/(?:OS )([0-9_]+)/g");
string osVersion = match.Groups[0].Value; // is ""

I'm not very knowledgeable about Regular Expressions, and can't see what I'm doing wrong. Most of the pages I've read are about people having issues going from C# to JS, and hitting issues due to JS not supporting everything that C# does. Is there a difference in syntax between the two that would cause this?

Upvotes: 0

Views: 838

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

Remove the / and /g

@"(?:OS )([0-9_]+)"

Output

OS 7_0

DEMO

If you want to use global search, use Regex.Matches, it will return more than one matches if any.

Searches an input string for all occurrences of a regular expression and returns all the matches.

Upvotes: 3

Related Questions