[英]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? 怎么了?
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 您颠倒了
(
。的顺序。请注意,组将为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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.