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
Examples:
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):
boolean doesMatch = "your string".matches( "[a-zA-Z]*" );
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
Statements that contain no letters do not match the expression.
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
The regular expression you want is [a-zA-Z]
, but you need to use the find()
method.
This page will let you test regular expressions against input.