【发布时间】:2018-12-20 22:29:51
【问题描述】:
我有一个正则表达式,其任务与此类似。这个人想要查找价格 (demo),其中美元符号必须在数字之前或之后,但不能两者兼而有之。
\b # "word" boundary
(?<=\$) # Assert that current position is preceded by $
\d+\b # digits, boundary
(?!\$) # Assert that current position is not followed by $
| # alternation
\b # boundary
(?<!\$) # Assert that current position not preceded by $
\d+\b # digits, boundary
(?=\$) # Assert that current position is followed by $
PCRE 中有没有一种方法可以使用条件来对条件进行类似操作。 (demo)
( # capture 1, because we can't quantify lookarounds
(?<=\$) # Asserts that $ precedes current position
)? # close capture 1, make it "optional" (0 or 1 times)
\b # boundary
\d+ # digits
\b # boundary
(?(1) # conditional that capture #1 was a success
(?!\$) # if successful, assert that it is not followed by a #
|
(?=\$) # unsuccessful, assert that this position is followed by a $
)
注意:单词边界很重要,因此两者都要捕获整数,否则正则表达式会后退一步,从多位数字中剪掉一个数字。
上面的两个表达式都匹配 $15 和 16$,但不是 $17$,因为它们应该匹配。如果没有边界,它们将匹配 17 美元中的 15 美元、16 美元和 1 美元。
【问题讨论】: