本着polygenelubricants'努力用正則表達式來做愚蠢的事情, 我當前嘗試讓.NET正則表達式引擎爲我乘法。與.NET正則表達式相乘
這當然沒有實用價值,而是純粹的理論練習。
到目前爲止,我已經到了這個怪物,它應該檢查1的數量乘以2的數量是否等於字符串中的3的數量。
Regex regex = new Regex(
@"
^
(1(?<a>))* # increment a for each 1
(2(?<b>))* # increment b for each 2
(?(a) # if a > 0
(
(?<-a>) # decrement a
(3(?<c-b>))* # match 3's, decrementing b and incrementing c until
# there are no 3's left or b is zero
(?(b)(?!)) # if b != 0, fail
(?<b-c>)* # b = c, c = 0
)
)* # repeat
(?(a)(?!)) # if a != 0, fail
(?(c)(?!)) # if c != 0, fail
$
", RegexOptions.IgnorePatternWhitespace);
不幸的是,它不工作,我不知道爲什麼。我評論它向你展示我認爲引擎應該做什麼,但我可能會在這裏。 輸出示例:
regex.IsMatch("123") // true, correct
regex.IsMatch("22") // true, correct
regex.IsMatch("12233") // false, incorrect
regex.IsMatch("11233"); // true, correct
任何想法都歡迎!
尼斯分析,謝謝!我會看看我是否可以解決這個問題...... =) – Jens 2010-09-27 06:16:09