简体   繁体   English

字符串 C# 中正则表达式的第 n 个匹配项的索引

[英]index of nth match of regular expression in a string C#

Can anyone please help me in finding the index of 5th match of the Regex (matches * not inside double quotes) in the following string?任何人都可以帮我找到以下字符串中正则表达式的第 5 个匹配项的索引(匹配 * 不在双引号内)?

ABC*DEF*PQR*"LMN*ABC"*XYZ*MNO*ABC*XYZ

ie 25 (just before MNO)即 25(就在 MNO 之前)

please help with the C# code to write the value 25 on the console output.请帮助 C# 代码在控制台输出上写入值 25。

I used the Regex: \\*(?=([^"]*"[^"]*")*[^"]*$)我使用了正则表达式: \\*(?=([^"]*"[^"]*")*[^"]*$)

Thanks!谢谢!

Following is a regex that will solve the problem.以下是可以解决问题的正则表达式。 Only limitation is if you enter more than present double quotes in the string, it will lead to catastrophic backtracking唯一的限制是,如果您在字符串中输入的双引号超过当前的双引号,则会导致灾难性的回溯

(?:(?:(?:[^*"]*)(?:"[^"]*")*)*(\*)){5}

Regex Demo正则表达式演示

string text = "ABC*DEF*PQR*\"LMN* ABC\"*XYZ*MNO*ABC*XYZ";
string pattern = "\\*(?=([^\"]*\"[^\"]*\")*[^\"]*$)";

var matches = Regex.Matches(text, pattern);

Console.WriteLine(matches[4].Index); // indexing from 0, so 4, not 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM