0

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?

2
  • 1
    Try to debug your regex with regexhero.net Commented Sep 11, 2014 at 10:39
  • Both that and dotnetfiddle.net from Yuliam's answer look really helpful. Wish I'd found them a couple of hours ago :) Commented Sep 11, 2014 at 10:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.