Util.ClearResults();
string tst = String.Join("", DateRange.Take(10).Select(d => d.DocHistory));
var matches = Regex.Matches (tst, "(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,2}assigned by(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,2}", RegexOptions.Multiline);
matches.Dump("Regex Matches");
foreach(var match in matches)
{
match.Dump("Ind Match");
}
我有这段代码,并且似乎可以正确地获取“值”,但是并没有从中分解出特定的值:
我有类似以下的字符串:“请求由Jack Arm在2018年8月16日关闭,受让人#1 James Arye由Scotty Shep在2018年8月16日分配,请求由Mac Weaver在2018年8月16日提交,由Mac Weaver在2018年8月16日创建的请求”
我正在尝试提取“ assign by”左侧和右侧的名称,但我收到“ Scotty Shep分配的James Arye” ...是否有办法将其拆分为“值”将其与正则表达式分成3个变量?
答案 0 :(得分:2)
您需要在需要获取的部分周围使用捕获组:
((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,2})assigned by((?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,2})
^ ---------- Group 1 ----------- ^ ^ ---------- Group 2----------- ^
请参见regex demo
var s = "Request closed by Jack Arm on 08/16/2018,Assignee #1 James Arye assigned by Scotty Shep on 08/16/2018,Request submitted by Mac Weaver on 08/16/2018,Request created by Mac Weaver on 08/16/2018";
var pattern = @"((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,2})assigned by((?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,2})";
var matches = Regex.Matches(s, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value.Trim());
Console.WriteLine(match.Groups[2].Value.Trim());
}
输出:
James Arye
Scotty Shep