开发者

How do I find if string has at least one character using regex?

Examples:

  1. "1 name": Should say it has characters
  2. "10,000": OK
  3. "na123me": Should say it has characters
  4. "na 123, 000": Shoul开发者_Go百科d say it has characters


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 


 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.


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.

http://www.fileformat.info/tool/regex.htm


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]*" );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜