当我尝试使用正则表达式拆分字符串时,由MatchCollection返回的MatchCollection.Matches
仅包含其自身的字符串,而不包含组。
所以这是我的正则表达式: string pattern = @"^(\w[.])\s*(\w+)$";
和一个示例字符串: W.Test
我希望MatchCollection具有2个元素W.
,Test
但是看起来不起作用。
您需要从捕获组中返回匹配的上下文。该组属性获取正则表达式中捕获的群体。
string pattern = @"^(\w[.])\s*(\w+)$";
string input = "W.Test";
Match match = Regex.Match(input, pattern);
if (match.Success) {
Console.WriteLine(match.Groups[1].Value); //=> 'W.'
Console.WriteLine(match.Groups[2].Value); //=> 'Test'
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句