我需要一个允许字符串的正则表达式,除非在任何时候一个组中有 6 个或更多数字。
我当前的错误正则表达式:
^([a-zA-Z ]*)|(\d{0,5})$
匹配:
teststring 12345
teststring
1234 teststring
teststring 123 teststring
test1234string
不匹配:
1234567 teststring
teststring 123456
test123456789string
我希望有人能提供帮助。 谢谢大家
更新: 这个正则表达式完成了工作:
^(?!.*\d{6}).*$
谢谢@WiktorStribiżew
最佳答案
匹配没有 6 个连续数字的字符串的模式是
^(?!.*\d{6}).*
regex demo is available here .如果内部可以有换行符,则需要添加一个 DOTALL 修饰符,使 .
匹配所有字符,包括换行符: (?s)^(?!.*\d{ 6}).*
.
详情
^
- 字符串的开始(隐含在matches()
中)(?!.*\d{6})
- 如果后跟 6 个连续数字的 0+ 个字符尽可能多,则匹配失败的否定前瞻.*
- 尽可能多的任意 0+ 个字符
在Java中,您可以通过以下方式使用它:
Boolean found = s.matches("(?s)(?!.*\\d{6}).*");
请注意,您可以尝试使用 Matcher#find
查找 6 位数字,如果找不到,则继续执行代码:
if (!Pattern.compile("\\d{6}").matcher(s).find()) {
// Cool, proceed
}
关于Java 正则表达式 - 仅当来自长字符串的组中有 n 个数字时才允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48203935/