如何查找所有匹配项
本文关键字:何查找 查找 | 更新日期: 2023-09-27 17:57:25
我想在"''abc/something/''abc/"的字符串中找到所有匹配项,而忽略something部分:
如果我的字符串是:
string str = @"'abc/something'abc/'abc/something'abc/;
我应该如何编写模式,以便获得 ''abc/something''abc/的两个匹配项?
因为在这种情况下使用 ^ 和 $ 来定义开头和结尾是行不通的,因为整个字符串确实以此开头和结尾。
你可以在这里尝试各种正则表达式: http://regexstorm.net/tester
但看起来你应该匹配''abc/
CaptureCollection 应该将所有匹配项放在一个组中,
一口气。
要么(?:.*?('''w+/))+
,要么(?:('''w+/)|.)+
举个例子。
(?:
.*?
( '' 'w+ / ) # (1)
)+
C#
string str = @"''adbc/''abrc/";
//Regex RxAbc = new Regex(@"(?:('''w+/)|.)+");
Regex RxAbc = new Regex(@"(?:.*?('''w+/))+");
Match _mAbc = RxAbc.Match(str);
if (_mAbc.Success)
{
CaptureCollection cc = _mAbc.Groups[1].Captures;
for (int i = 0; i < cc.Count; i++)
{
Console.WriteLine("{0}", cc[i].Value);
}
}
输出:
'adbc/
'abrc/
编辑 - 来自评论another example that is like this: @"'abc/something'abc/'abc/somethingELSE'abc/, and return 2 matches of 'abc/something'abc/
# ?:.*?(('''w+/).*?'2))+
(?:
.*?
( # (1 start)
( '' 'w+ / ) # (2)
.*?
'2
) # (1 end)
)+
C#
string str = @"'abcX/somethinghere'abcX/'abcY/there'abcY/'abcZ/'abcZ/";
Regex RxAbc = new Regex(@"(?:.*?(('''w+/).*?'2))+");
Match _mAbc = RxAbc.Match(str);
if (_mAbc.Success)
{
CaptureCollection ccAbcToAbc = _mAbc.Groups[1].Captures;
CaptureCollection ccAbc = _mAbc.Groups[2].Captures;
for (int i = 0; i < ccAbcToAbc.Count; i++)
{
Console.WriteLine("Found keyword {0}, in string {1}", ccAbc[i].Value, ccAbcToAbc[i].Value);
}
Console.WriteLine("------------------------'n");
}
输出:
Found keyword 'abcX/, in string 'abcX/somethinghere'abcX/
Found keyword 'abcY/, in string 'abcY/there'abcY/
Found keyword 'abcZ/, in string 'abcZ/'abcZ/
相同的代码不同的输入
输入 = @"'abc/somethinghere'abc/'abc/there'abc/'abc/'abc/"
输出:
Found keyword 'abc/, in string 'abc/somethinghere'abc/
Found keyword 'abc/, in string 'abc/there'abc/
Found keyword 'abc/, in string 'abc/'abc/