java - How to test if a String contains both letter and number

前端 未结 7 1226
轻奢々
轻奢々 2020-12-16 01:07

I need a regex which will satisfy both conditions.

It should give me true only when a String contains both A-Z and 0-9.

Here\'s what I\'ve tried:

相关标签:
7条回答
  • 2020-12-16 01:33

    It easier to write and read if you use two separate regular expressions:

    String s  =  "blah-FOO-test-1-2-3";
    
    String numRegex   = ".*[0-9].*";
    String alphaRegex = ".*[A-Z].*";
    
    if (s.matches(numRegex) && s.matches(alphaRegex)) {
        System.out.println("Valid: " + input);
    }
    

    Better yet, write a method:

    public boolean isValid(String s) {
        String n = ".*[0-9].*";
        String a = ".*[A-Z].*";
        return s.matches(n) && s.matches(a);
    }
    
    0 讨论(0)
提交回复
热议问题