简体   繁体   中英

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?

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.

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