[英]Multiplication with .NET regular expressions
本着polygenelubricants努力用正則表達式做傻事的精神,我目前試圖讓.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
歡迎任何想法!
我很確定問題出在這一行:
(?<b-c>)*
從我所知道的,沒有文字可以匹配,正則表達式拒絕匹配它不止一次。 我將正則表達式簡化為以下內容:
(1(?<a>))*
(?(a)(?<-a>))*
(?(a)(?!))
傳遞1
失敗111
。 還試過(?<-a>)*
。 沒有不同。 但是,將其更改為
(1(?<a>))*
(?(a)((?<-a>)(2(?<b>))(?<-b>)))*
(?(a)(?!))
通過12
和111222
。 因此,從""
匹配""
到匹配某事會導致正則表達式按預期工作。
回到你的原始正則表達式,我的猜測是(?<bc>)*
僅匹配0-1次,這解釋了為什么在你的字符串中有一個2工作,但有多個失敗。
使用11
的字符串也會失敗,它遵循相同的邏輯,因為它使整個匹配""
,這很可能意味着它只匹配一次,導致(?(a)(?!))
失敗。
通過Joel的輸入,我能夠使其工作,稍微修改算法以避免那些(?<bc>)*
行。
看吧:
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
(?(b) # if b > 0
(
(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
)
| # else ( b = 0 )
(
(3(?<b-c>))* # match 3's, decrementing c and incrementing b until
# there are no 3's left or c is zero
(?(c)(?!)) # if c != 0, fail
)
)
)
)* # repeat
(?(a)(?!)) # if a != 0, fail
$
", RegexOptions.IgnorePatternWhitespace);
我想給出一個ideone鏈接,但我得到的結果與我的不同。 也許是因為我使用的是.NET 4.0而他們沒有?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.