适用于3位数字条件的有效java正则表达式

时间:2017-09-22 09:30:22

标签: java regex

我试图单独匹配3位数字,但“不匹配”列表中的示例除外。

我在下面显示的当前正则表达式不能完全正常工作,我不知道如何针对所有用例调整它。

当前的Java Regex:

(^.*err.*[a-z].*$)|(^\d{3}$)|(^.*\d{3}\s\b$)

测试字符串:

The below items should match:
-----------------------------
123
Match the number in this sentence 123 as well
999

The below items should NOT match:
---------------------------------
1234
12345
123456
1234567

£123
$456

Err404
ERR404
err404
Err 404
ERR 404
err 404

there is err 404 on page
this err 1232222222222 as well

a string 12323 like this
asd
4444333322221111
4444 3333 2222 1111
Err123

02012341234
920 1234 1234

1 个答案:

答案 0 :(得分:0)

(?:(?<!err)\s+?)(\d{3})\b

尝试使用正则表达式here

正如Wiktor所指出的那样,它将与最后的920相匹配。

另请注意,我使用了不区分大小写的搜索。

正则表达式解释

(?:      #Non Capturing group START
(?<!     #Negative look-behind don't match if preceded by this
err      #Shouldn't precede by err NOTE that we've to use case insensitive flag
)        #END Negative look behind
\s+?     #Followed by multi optional space  
)        #End Non capturing group
(\d{3})  #Match exactly 3 digits
\b       #The 3 digits have end with a word boundary

<强> EDITED 根据javascript的要求更改答案

(err\s*?\d{1})|\s+(\d{3})\b


试用正则表达式here

所需比赛仅来自第2组。

正则表达式解释

(err\s*?\d{1})   #Group One thus exhausts matching any further and thus discarded.
\s+(\d{3})\b     #Matches all 3 digit groups occurring solely.

使用javascript版本here

再次编辑

(err\s*?\d{1})|[^\d]\s+(\d{3})(?:$|\s+(?!\d))

试用正则表达式here

Java脚本here

输出将是: -

123
123
999