Java 如何使用正则表达式查找字符串是否至少包含一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2876798/
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
How do I find if string has at least one character using regex?
提问by Vishal
Examples:
例子:
- "1 name": Should say it has characters
- "10,000": OK
- "na123me": Should say it has characters
- "na 123, 000": Should say it has characters
- “1 name”:应该说它有字符
- “10,000”:好的
- “na123me”:应该说它有字符
- “na 123, 000”:应该说它有字符
采纳答案by David M
The regular expression you want is [a-zA-Z]
, but you need to use the find()
method.
您想要的正则表达式是[a-zA-Z]
,但您需要使用该find()
方法。
This page will let you test regular expressions against input.
此页面将允许您针对输入测试正则表达式。
回答by tangens
With this line you can check if your string contains only of characters given by the regex (in this case a,b,c,...z and A,B,C,...Z):
通过这一行,您可以检查您的字符串是否仅包含正则表达式给出的字符(在本例中为 a,b,c,...z 和 A,B,C,...Z):
boolean doesMatch = "your string".matches( "[a-zA-Z]*" );
回答by npinti
public static void main(String[] args)
{
Pattern p = Pattern.compile("^([^a-zA-Z]*([a-zA-Z]+)[^a-zA-Z]*)+$");
Matcher m = p.matcher("1 name");
Matcher m1 = p.matcher("10,000");
Matcher m2 = p.matcher("na123me");
Matcher m3 = p.matcher("na 123, 000");
Matcher m4 = p.matcher("13bbbb13jdfgjd43534 fkgdfkgjk34 rktekjg i54 ");
if (m.matches())
System.out.println(m.group(1));
if (m1.matches())
System.out.println(m1.group(1));
if(m2.matches())
System.out.println(m2.group(1));
if(m3.matches())
System.out.println(m3.group(1));
if (m4.matches())
System.out.println(m4.group(1));
}
The above should match any letter in both lower and upper case. If the regex returns a match, the string has a letter in it.
以上应匹配任何大小写字母。如果正则表达式返回匹配项,则字符串中包含一个字母。
Result
结果
1 name
me
na 123, 000
i54
1个名字
我
不适用 123, 000
i54
Statements that contain no letters do not match the expression.
不包含字母的语句与表达式不匹配。
回答by OscarRyz
public class HasCharacters {
public static void main( String [] args ){
if( args[0].matches(".*[a-zA-Z]+.*")){
System.out.println( "Has characters ");
} else {
System.out.println("Ok");
}
}
}
Test
测试
$java HasCharacters "1 name"
Has characters
$java HasCharacters "10,000"
Ok
$java HasCharacters "na123me"
Has characters
$java HasCharacters "na 123, 000"
Has characters