【问题标题】:How to extract multiple values from Regex?如何从正则表达式中提取多个值?
【发布时间】:2019-02-01 08:34:09
【问题描述】:
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 日关闭请求,Scotty Shep 于 2018 年 8 月 16 日分配的受让人 #1 James Arye,Mac Weaver 于 2018 年 8 月 16 日提交的请求,Mac Weaver 于 2018 年 8 月 16 日创建的请求"

我正在尝试将名称提取到“分配者”的左侧和右侧,但我得到的是“Scotty Shep 分配的 James Arye”......有没有办法让它分开“ value" 用正则表达式找到了 3 个变量?

【问题讨论】:

  • 使用捕获组 - ((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,2})assigned by((?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,2}) - 然后 match.Groups[1].Valuematch.Groups[2].Value 将保留结果。
  • 数据是一行还是多行?
  • @jdweng 数据可以多行
  • @Wiktor Stribizew - 做得很好。这正是我所需要的。
  • @Wiktor Stribizew "match.Groups[1].Value" 给出了编译错误,匹配不包含 "Groups"...任何想法吗?

标签: c# regex regex-group


【解决方案1】:

您需要在需要获取的部分周围使用捕获组:

((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,2})assigned by((?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,2})
^ ---------- Group 1 ----------- ^           ^ ---------- Group 2-----------  ^

regex demo

C# 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

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2017-07-06
    • 2021-11-04
    相关资源
    最近更新 更多