/ / Regexで2つのキャプチャグループ - c#、正規表現

Regexで2つのキャプチャグループ - c#、regex

私は

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

これらの文字列を2つのグループにまとめる正規表現が欲しかった

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

だから私はこの正規表現を書いた

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

しかし、2つのグループの代わりに私は3つのグループ

最初の例で私は得る

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

どうしましたか?

回答:

回答№1は2

あなたが探している正規表現はおそらく

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

あなたは (。誰かが指摘するように、グループ0はすべて一致したテキストなので、グループは3になります。そう

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)
}