如何解决正则表达式匹配任何字符之间的正数和短语
我需要编写一个正则表达式来检查一个短语是否包含正数。我发现了这个:
[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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。