我想在下面以“ need”单词开头的字符串中捕获粗体值,而必须忽略以“ skip”和“ ignored”开头的其他字符串中的单词。我尝试了模式need.+?(:"(?'index'\w+)"[,}])
但它只找到第一个(以太值)值。如何仅使用RegEx获得所需的结果?
“ skip”:{“ A”:“ ABCD123”,“ B”:“ ABCD1234”,“ C”:“ ABCD1235”}
“需要”:{“ A”:“ ZABCD123”,“ B”:“ ZABCD1234”,“ C”:“ ZABCD1235”}
“ ignore”:{“ A”:“ SABCD123”,“ B”:“ SABCD1234”,“ C”:“ SABCD1235”}
最佳答案
我们将找到need
并将找到的内容分组为Named Match Group => Captures。将有两组,一组名为Index
容纳A | B | C
,然后一组名为Data
。
匹配项将保存我们的数据,如下所示:
从那里我们将把它们加入字典中:
这是执行此魔术的代码:
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/