java 什么是匹配除 1、2 和 25 之外的所有数字的正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25553470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's a regex that matches all numbers except 1, 2 and 25?
提问by ktulinho
There's an input of Strings that are composed of only digits, i.e. integer numbers. How to write a regex that will accept all the numbers except numbers 1, 2 and 25?
有一个仅由数字组成的字符串输入,即整数。如何编写一个接受除数字 1、2 和 25 之外的所有数字的正则表达式?
I want to use this inside the record identificationof BeanIO (which supports regex) to skip some records that have specific values.
我想在BeanIO(支持正则表达式)的记录标识中使用它来跳过一些具有特定值的记录。
I reach this point ^(1|2|25)$
, but I wanted the opposite of what this matches.
我达到了这一点^(1|2|25)$
,但我想要与此匹配的相反内容。
回答by Joseph Silber
Not that a regex is the best tool for this, but if you insist...
并不是说正则表达式是最好的工具,但如果你坚持......
Use a negative lookahead:
使用负前瞻:
/^(?!(?:1|2|25)$)\d+/
See it here in action: http://regexr.com/39df2
在此处查看实际操作:http: //regexr.com/39df2
回答by p.s.w.g
You could use a pattern like this:
你可以使用这样的模式:
^([03-9]\d*|1\d+|2[0-46-9]\d*|25\d+)$
Or if your regex engine supports it, you could just use a negative lookahead assertion ((?!…)
) like this:
或者,如果您的正则表达式引擎支持它,您可以(?!…)
像这样使用否定前瞻断言 ( ):
^(?!1$|25?$)\d+$
However, you'd probably be better off simply parsing the number in code and ensuring that it doesn't equal one of the prohibited values.
但是,您最好简单地解析代码中的数字并确保它不等于禁止值之一。
回答by vks
(?!^1$|^2$|^25$)(^\d+$)
This should work for your case.
这应该适用于您的情况。
回答by FrobberOfBits
See this related question on stackoverflow.
You shouldn't try to write such a regular expression since most languages don't support the complement of regular expressions.
您不应该尝试编写这样的正则表达式,因为大多数语言不支持正则表达式的补充。
Instead what you should do is write a regex that matches only those three things: ^(1|2|25)$
- and then in your code you should check to see if this regex matches \d+
and fails to match this other one, e.g.:
相反,您应该做的是编写一个只匹配这三件事的正则表达式: ^(1|2|25)$
- 然后在您的代码中,您应该检查这个正则表达式是否匹配\d+
并且无法匹配另一个,例如:
`if($myStr =~ m/\d+/ && !($myStr =~ m/^(1|2|25)$/))`