问题描述
我需要编写一个正则表达式来检查一个短语是否包含正数。我发现了这个:
[1-9]\d* (left|remaining).*$
但它不适用于负数。所以我想检查单词“left”或“remaining”是否跟在正数后面。 这些是测试用例
0 left
1 left
2 left
3 left
0 remaining
1 remaining
2 remaining
you have 3 left
(13 left)
there are 12 remaining today
You have (-12 left) today
There are (3 left)
-15 remaining today
you have -24 left today
解决方法
使用
(?<!-)\b[1-9]\d*\s+(left|remaining)
见proof。
说明
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
[1-9] any character of: '1' to '9'
--------------------------------------------------------------------------------
\d* digits (0-9) (0 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
\s+ whitespace (\n,\r,\t,\f,and " ") (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
left 'left'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
remaining 'remaining'
--------------------------------------------------------------------------------
) end of \1