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
- "1111"=>false
- "AAA" =>false
- "1A" => true
- "A1" => true
- "111AAA111"=>true
- "AAA11111AA"=>true
- "#AA111BBB"=>false
- "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.