d.DocHistory)); var-6ren">
gpt4 book ai didi

c# - 如何从正则表达式中提取多个值?

转载 作者:行者123 更新时间:2023-11-30 22:59:42 24 4
gpt4 key购买 nike

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 于 08/16/2018 创建的请求"

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

最佳答案

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

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

参见 regex demo

enter image description here

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

关于c# - 如何从正则表达式中提取多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com