Mitchell
Mitchell

Reputation: 169

Get a string using regular expressions

I've been trying to capture a string that is between two commas. I created the following code:

Regex.Match(forReg, @"\,([^,]*)\,");

the forReg string will look like this

forReg = "123456,x,NULL"

Where x is an integer less than 999.

The first problem is I'm not sure how to use the string that I've captuered using Regex.Match and the second problem is I'm not even sure if I've done the Regex code correctly. I've looked up several threads with similar issues but can't seem to make any more progress.

Upvotes: 0

Views: 50

Answers (2)

hwnd
hwnd

Reputation: 70750

You can access the captured match by using the Match.Groups property, and secondly you do not need to escape the comma's inside your regular expression because it is not a character of special meaning.

String forReg = "123456,77,NULL";
Match match   = Regex.Match(forReg, @",([^,]*),");

if (match.Success) {
   Console.WriteLine(match.Groups[1].Value); //=> "77"
} 

Upvotes: 1

Mitchell
Mitchell

Reputation: 169

Okay so this worked

            Match match = Regex.Match(forReg, @"\,([^,]*)\,");
            if (match.Success)
            {
                string age = match.Groups[1].Value;
            }

Upvotes: 1

Related Questions