3 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
進(jìn)行三種不同的匹配,并使用程序中條件邏輯處理三種情況的組合。你不需要處理一個(gè)巨大的正則表達(dá)式中的所有東西。
編輯:讓我擴(kuò)大一點(diǎn),因?yàn)閱?wèn)題變得更有趣:-)
您在此嘗試捕獲的一般想法是匹配某個(gè)正則表達(dá)式模式,但不是當(dāng)測(cè)試字符串中存在某些其他(可能是任何數(shù)字)模式時(shí)。幸運(yùn)的是,您可以利用您的編程語(yǔ)言:保持正則表達(dá)式簡(jiǎn)單,只需使用復(fù)合條件。最好的做法是在可重用的組件中捕獲這個(gè)想法,所以讓我們創(chuàng)建一個(gè)實(shí)現(xiàn)它的類(lèi)和方法:
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)); } }}
所以上面,我們?cè)O(shè)置了搜索字符串(五位數(shù)),多個(gè)異常字符串(你的s1,s2和s3),然后嘗試匹配幾個(gè)測(cè)試字符串。打印結(jié)果應(yīng)如每個(gè)測(cè)試字符串旁邊的注釋中所示。

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
你的要求是,在所有情況下都不可能滿(mǎn)足于parens。也就是說(shuō),如果你能以某種方式找到(
左邊和)
右邊的,它并不總是意味著你在內(nèi)部。例如。
(....) + 55555 + (.....)
-不,在括號(hào)內(nèi)部竟然有(
和)
左,右
現(xiàn)在你可能會(huì)認(rèn)為自己很聰明,(
只有你)
以前沒(méi)有遇到過(guò)左邊,反之亦然。這不適用于這種情況:
((.....) + 55555 + (.....))
- 即使有關(guān)閉)
,(
左邊和右邊,也在內(nèi)部。
不可能發(fā)現(xiàn)你是否在使用正則表達(dá)式的parens中,因?yàn)檎齽t表達(dá)式無(wú)法計(jì)算已經(jīng)打開(kāi)了多少個(gè)parens以及關(guān)閉了多少個(gè)parens。
考慮這個(gè)更簡(jiǎn)單的任務(wù):使用正則表達(dá)式,找出字符串中的所有(可能是嵌套的)parens是否已關(guān)閉,這是(
您需要查找的每一個(gè))
。你會(huì)發(fā)現(xiàn)它是不可能解決的,如果你用正則表達(dá)式無(wú)法解決這個(gè)問(wèn)題,那么你無(wú)法弄清楚一個(gè)單詞是否在所有情況下都在parens中,因?yàn)槟銦o(wú)法弄清楚字符串中的某個(gè)位置所有前面(
都有相應(yīng)的)
。
- 3 回答
- 0 關(guān)注
- 1442 瀏覽
添加回答
舉報(bào)