3 回答

TA貢獻1844條經驗 獲得超8個贊
進行三種不同的匹配,并使用程序中條件邏輯處理三種情況的組合。你不需要處理一個巨大的正則表達式中的所有東西。
編輯:讓我擴大一點,因為問題變得更有趣:-)
您在此嘗試捕獲的一般想法是匹配某個正則表達式模式,但不是當測試字符串中存在某些其他(可能是任何數字)模式時。幸運的是,您可以利用您的編程語言:保持正則表達式簡單,只需使用復合條件。最好的做法是在可重用的組件中捕獲這個想法,所以讓我們創建一個實現它的類和方法:
using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;public class MatcherWithExceptions { private string m_searchStr; private Regex m_searchRegex; private IEnumerable<Regex> m_exceptionRegexes; public string SearchString { get { return m_searchStr; } set { m_searchStr = value; m_searchRegex = new Regex(value); } } public string[] ExceptionStrings { set { m_exceptionRegexes = from es in value select new Regex(es); } } public bool IsMatch(string testStr) { return ( m_searchRegex.IsMatch(testStr) && !m_exceptionRegexes.Any(er => er.IsMatch(testStr)) ); }}public class App { public static void Main() { var mwe = new MatcherWithExceptions(); // Set up the matcher object. mwe.SearchString = @"\b\d{5}\b"; mwe.ExceptionStrings = new string[] { @"\.$" , @"\(.*" + mwe.SearchString + @".*\)" , @"if\(.*" + mwe.SearchString + @".*//endif" }; var testStrs = new string[] { "1." // False , "11111." // False , "(11111)" // False , "if(11111//endif" // False , "if(11111" // True , "11111" // True }; // Perform the tests. foreach (var ts in testStrs) { System.Console.WriteLine(mwe.IsMatch(ts)); } }}
所以上面,我們設置了搜索字符串(五位數),多個異常字符串(你的s1,s2和s3),然后嘗試匹配幾個測試字符串。打印結果應如每個測試字符串旁邊的注釋中所示。

TA貢獻1859條經驗 獲得超6個贊
你的要求是,在所有情況下都不可能滿足于parens。也就是說,如果你能以某種方式找到(
左邊和)
右邊的,它并不總是意味著你在內部。例如。
(....) + 55555 + (.....)
-不,在括號內部竟然有(
和)
左,右
現在你可能會認為自己很聰明,(
只有你)
以前沒有遇到過左邊,反之亦然。這不適用于這種情況:
((.....) + 55555 + (.....))
- 即使有關閉)
,(
左邊和右邊,也在內部。
不可能發現你是否在使用正則表達式的parens中,因為正則表達式無法計算已經打開了多少個parens以及關閉了多少個parens。
考慮這個更簡單的任務:使用正則表達式,找出字符串中的所有(可能是嵌套的)parens是否已關閉,這是(
您需要查找的每一個)
。你會發現它是不可能解決的,如果你用正則表達式無法解決這個問題,那么你無法弄清楚一個單詞是否在所有情況下都在parens中,因為你無法弄清楚字符串中的某個位置所有前面(
都有相應的)
。
- 3 回答
- 0 關注
- 1447 瀏覽
添加回答
舉報