我正在用 Swift 构建一个需要检查这些特定情况的正则表达式:
如果找到则匹配:
AB*5+4
AB+4*5
AB+4
AB*5
AB
AB+54.45
AB+50.49*54
如果找到则不匹配:
AB+4+5
AB*4*5
AB*0
只能有零到两个运算符(+
或*
),但如果有两个,则不能相同。与 0
的乘积不应匹配。
我构建的正则表达式如下:
[A-Z]{2}(\+|\*)[1-9]{1,}(?:(?(?=\1)(\+|\\*))[1-9]{1,})?
主要问题是我无法预测第一个捕获组中的条件,所以我无法检查如下内容:if *
in the first captured group then +
反之亦然。
谁能帮帮我?
最佳答案
您需要使用否定前瞻 ((?!...)
),如下所示:
[A-Z]{2}(\+|\*)\d+(?!\1)((\+|\*)\d+)?
如 the docs 中所述, 一个否定的先行断言是
True if the parenthesized pattern does not match at the current input position. Does not advance the input position.
上面的正则表达式匹配:
[A-Z]{2}
2 个字母(\+|\*)
+
或*
\d+
1个或多个数字(?!\1)
后面不能跟第一个相同的符号(+
或*
)((\+|\*)\d+)?
可选地,另一个+
或*
后跟一个或多个数字<
Here's a demo它通过了您作为示例列出的所有案例,并符合您在评论中的限制。
关于regex - 匹配最多两个运算符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41253769/