Sachin Kainth
Sachin Kainth

Reputation: 46740

Two Capturing Groups in Regex

I have string such as

(1)ABC(Some other text)
(2343)DEFGHIJ
(99)Q

I wanted a regex that would capture these strings into two groups like so

ist: (1) 2nd: ABC(Some other text)
1st: (2343) 2nd: DEFGHIJ
ist: (99) 2nd: Q

So I wrote this Regex

var regex new Regex("^\\((\\d+)(.*)\\)");
Match match = regex.Match(str);

But instead of the two groups I expected I get three groups

In the first example I get

(1)ABC(Some other text)
1
)ABC(Some other text

What's wrong?

Upvotes: 0

Views: 111

Answers (1)

xanatos
xanatos

Reputation: 111840

The regex you are looking for is probably

@"^(\(\d+\))(.*)"

You reversed the order of the (. Note that the groups will be 3, because as someone pointed out, the group 0 is all the matched text. So

string str = "(1)ABC(Some other text)";
var regex = new Regex(@"^(\(\d+\))(.*)");
Match match = regex.Match(str);

if (match.Success)
{
    string gr1 = match.Groups[1].Value; // (1)
    string gr2 = match.Groups[2].Value; // (Some other text)
}

Upvotes: 2

Related Questions