[英]index of nth match of regular expression in a string C#
任何人都可以幫我找到以下字符串中正則表達式的第 5 個匹配項的索引(匹配 * 不在雙引號內)?
ABC*DEF*PQR*"LMN*ABC"*XYZ*MNO*ABC*XYZ
即 25(就在 MNO 之前)
請幫助 C# 代碼在控制台輸出上寫入值 25。
我使用了正則表達式: \\*(?=([^"]*"[^"]*")*[^"]*$)
謝謝!
以下是可以解決問題的正則表達式。 唯一的限制是,如果您在字符串中輸入的雙引號超過當前的雙引號,則會導致災難性的回溯
(?:(?:(?:[^*"]*)(?:"[^"]*")*)*(\*)){5}
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.