2

I need the regex expression which would accept only alphanumeric data.

Say for eg: ABC12DG - should allow this

if input data is 123000 - should not allow as it is only numeric.

I have tried this

say a is a string which contains the input data

then a.matches("^[a-zA-Z0-9]+$") this allows both the first and second input as above

I only want it to allow the alphanumeric input , not just numeric or alphabets How to do that

2 Answers 2

4

Use negative lookahead or alternation operator.

a.matches("^(?![A-Za-z]+$)(?!\\d+$)[a-zA-Z0-9]+$");
  • (?![A-Za-z]+$) asserts that the match won't contain only alphabets.
  • (?!\\d+$) asserts that the match won't contain only digits.
  • [a-zA-Z0-9]+ Matches one or more alphanumeric characters.

or

a.matches("^[a-zA-Z0-9]*(?:[a-zA-Z]\\d|\\d[a-zA-Z])[a-zA-Z0-9]*$");
Sign up to request clarification or add additional context in comments.

1 Comment

what is this expression.. can u explain pls
1

You can try this Regex for your text:

    String reg = "\\p{Alpha}+\\d+";
    String str1 = "It &* is %$ now OK 2015";
    String str2 = "ItisnowOK2015";
    String str3 = "888";
    String str4 = "aaa";
    System.out.println("str1 = "+str1.matches(reg));
    System.out.println("str2 = "+str2.matches(reg));
    System.out.println("str3 = "+str3.matches(reg));
    System.out.println("str4 = "+str4.matches(reg));

And is the result:

str1 = false
str2 = true
str3 = false
str4 = false

7 Comments

can you give it in this way like a-z A-Z , that would be good
not this way.. am looking for regex which includes this kind of expression a-zA-Z 0-9 instead of Alnum
Yourself said that: Regular expression in java to allow only alphanumeric input data. Then this regex just do what you asked
@BahramdunAdil your regex should also allow aaa and 888 . But this is not op expects..
I have already wrote a test code in the answer, did you see OR NOT
|

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.