gpt4 book ai didi

c# - 查找特定子字符串中匹配的乘法组

转载 作者:行者123 更新时间:2023-11-30 23:12:43 26 4
gpt4 key购买 nike

我想捕获下面字符串中以“need”字开头的粗体值,而其他字符串中以“skip”和“ignored”开头的字必须被忽略。我尝试了模式

需要.+?(:"(?'index'\w+)"[,}])

但它只找到第一个(重点)值。如何仅使用 RegEx 获得所需的结果?

“跳过”:{“A”:“ABCD123”,“B”:“ABCD1234”,“C”:“ABCD1235”

"需要":{"A":"ZABCD123","B":"ZABCD1234","C":"ZABCD1235

“忽略”:{“A”:“SABCD123”,“B”:“SABCD1234”,“C”:“SABCD1235”}

最佳答案

我们要找到需要并将找到的内容分组到Named Match Group中=> Captures .将有两组,一组名为 Index,其中包含 A |乙 | C 然后是一个名为 Data 的文件。

比赛将保存我们的数据,如下所示:

enter image description here

从那里我们将它们加入字典:

enter image description here

下面是实现这个魔法的代码:

string data =
@"""skip"" : {""A"":""ABCD123"",""B"":""ABCD1234"",""C"":""ABCD1235""}
""need"" : {""A"":""ZABCD123"",""B"":""ZABCD1234"",""C"":""ZABCD1235""}
""ignore"" : {""A"":""SABCD123"",""B"":""SABCD1234"",""C"":""SABCD1235""}";

string pattern = @"
\x22need\x22\s *:\s *{ # Find need
( # Beginning of Captures
\x22 # Quote is \x22
(?<Index>[^\x22] +) # A into index.
\x22\:\x22 # ':'
(?<Data>[^\x22] +) # 'Z...' Data
\x22,? # ',(maybe)
)+ # End of 1 to many Captures";


var mt = Regex.Match(data,
pattern,
RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);

// Get the data capture into a List<string>.
var captureData = mt.Groups["Data"].Captures.OfType<Capture>()
.Select(c => c.Value).ToList();

// Join the index capture data and project it into a dictionary.
var asDictionary = mt.Groups["Index"]
.Captures.OfType<Capture>()
.Select((cp, iIndex) => new KeyValuePair<string,string>
(cp.Value, captureData[iIndex]) )
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value );

关于c# - 查找特定子字符串中匹配的乘法组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942757/

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