我有
之类的字符串(1)ABC(Some other text)
(2343)DEFGHIJ
(99)Q
我想要一个正则表达式,将这些字符串捕获到两个组中,如此
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);
但是我预计我会得到三组
而不是两组在第一个例子中,我得到了
(1)ABC(Some other text)
1
)ABC(Some other text
怎么了?
答案 0 :(得分:2)
你正在寻找的正则表达式可能是
@"^(\(\d+\))(.*)"
您颠倒了(
的顺序。请注意,组将为3,因为有人指出,组0是所有匹配的文本。所以
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)
}