Home > database >  How regex pattern write to check at least one string and number in Java?
How regex pattern write to check at least one string and number in Java?

Time:11-02

I have an issue related to regex check at least one string and number which exclude any sign like @!#%^&*. I have read many articles but I still can not find the correct answer as my expectation result.

Example: I have a string like : 111AB11111

My expectation result: If input string

  1. "1111"=>false
  2. "AAA" =>false
  3. "1A" => true
  4. "A1" => true
  5. "111AAA111"=>true
  6. "AAA11111AA"=>true
  7. "#AA111BBB"=>false
  8. "111AAAA$"=>false

Which java regex patter can show above mentioned cases Thank for your value time for checking and suggestion Thank you!!

CodePudding user response:

You could use String#matches with the following regex pattern:

^[A-Z0-9]*(?:[0-9][A-Z0-9]*[A-Z]|[A-Z][A-Z0-9]*[0-9])[A-Z0-9]*$

Sample Java code:

List<String> inputs = Arrays.asList(new String[] { "111AB", "111", "AB", "111AB$" });
for (String input : inputs) {
    if (input.matches("[A-Z0-9]*(?:[0-9][A-Z0-9]*[A-Z]|[A-Z][A-Z0-9]*[0-9])[A-Z0-9]*")) {
        System.out.println(input   " => VALID");
    }
    else {
        System.out.println(input   " => INVALID");
    }
}

This prints:

111AB => VALID
111 => INVALID
AB => INVALID
111AB$ => INVALID

Note that the regex pattern actually used with String#matches do not have leading/trailing ^/$ anchors. This is because the matches API implicitly applies the regex pattern to the entire string.

For an explanation of the regex pattern, it simply tries to match an input with has at least one digit or letter, in any order.

CodePudding user response:

This would accomplish your goal:

^(?:[0-9] [A-Za-z]|[A-Za-z] [0-9])[A-Za-z0-9]*$

Digits preceding alpha, or alphas preceding a digit, followed by only alphas and digits.

  • Related