Java 包含一个或多个字母的字符串的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23000258/
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
Regular Expression for a string that contains one or more letters somewhere in it
提问by codenamepenryn
What would be a regular expression that would evaluate to true if the string has one or more letters anywhere in it.
如果字符串中的任何位置有一个或多个字母,那么它的计算结果为真的正则表达式是什么?
For example:
例如:
1222a3999
would be true
1222a3999
会是真的
a222aZaa
would be true
a222aZaa
会是真的
aaaAaaaa
would be true
aaaAaaaa
会是真的
but:
但:
1111112())--
would be false
1111112())--
会是假的
I tried: ^[a-zA-Z]+$
and [a-zA-Z]+
but neither work when there are any numbers and other characters in the string.
我想:^[a-zA-Z]+$
和[a-zA-Z]+
,但没有工作的时候有字符串中的任何数字和其他字符。
采纳答案by amit
.*[a-zA-Z].*
.*[a-zA-Z].*
The above means one letter, and before/after it - anything is fine.
上面的意思是一个字母,在它之前/之后 - 一切都很好。
In java:
在Java中:
String regex = ".*[a-zA-Z].*";
System.out.println("1222a3999".matches(regex));
System.out.println("a222aZaa ".matches(regex));
System.out.println("aaaAaaaa ".matches(regex));
System.out.println("1111112())-- ".matches(regex));
Will provide:
会提供:
true
true
true
false
as expected
正如预期的那样
回答by Barmar
This regexp should do it:
这个正则表达式应该这样做:
[a-zA-Z]
It matches as long as there's a single letter anywhere in the string, it doesn't care about any of the other characters.
只要字符串中的任何地方只有一个字母,它就会匹配,它不关心任何其他字符。
[a-zA-Z]+
should have worked as well, I don't know why it didn't for you.
应该也有效,我不知道为什么它不适合你。
回答by Qix - MONICA WAS MISTREATED
^.*[a-zA-Z].*$
^.*[a-zA-Z].*$
Depending on the implementation, match()
functions check if the entirestring matches (which is probably why your [a-zA-Z]
or [a-zA-Z]+
patterns didn't work).
根据实现,match()
函数会检查整个字符串是否匹配(这可能是您的[a-zA-Z]
或[a-zA-Z]+
模式不起作用的原因)。
Either use match()
with the above pattern or use some sort of search()
method instead.
要么使用match()
上述模式,要么使用某种search()
方法。
回答by Darren
.*[a-zA-Z]?.*
.*[a-zA-Z]?.*
Should get you the result you want.
应该让你得到你想要的结果。
The period matches any character except new line, the asterisk says this should exist zero or more times. Then the pattern [a-zA-Z]? says give me at least one character that is in the brackets because of the use of the question mark. Finally the ending .* says that the alphabet characters can be followed by zero or more characters of any type.
句点匹配除新行之外的任何字符,星号表示这应该存在零次或多次。那么模式[a-zA-Z]?说由于使用了问号,请至少给我一个括号中的字符。最后的结尾 .* 表示字母字符后面可以跟零个或多个任何类型的字符。