本着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