0

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!!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Biegenleisen Thank you brother for your answer, it works but I want to exclude any special character and sign like : \t\n &#$%@& how can I do that.
Edit your question and reveal the actual problem. Note that \t is not typically considered a special character.
Thank @Tim Biegeleisen again for your answer, I just update my question please you help to check how can I exclude those sign. Which regex should be add on your provided above.
@James I have updated my answer per your latest requirements.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.