1

i need to get the value which only Alphanumeric and it can be of anything which comes under this

1. asd7989 - true
2. 7978dfd - true
3. auo789dd - true
4. 9799 - false
5.any special characters - false

i tried with the following but it does not give expected result

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts.action.ActionMessage;

public class Test {

  public static void main(String[] args) {

      Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
      Matcher matcher = pattern.matcher("465123");
      if(matcher.matches()) {
           System.out.println("match");
      }else{
          System.out.println("not match");
      }
  }
}

the result should actually be not match but i get as match

1
  • I wouldn't use Regex for this, you can write a simple function that iterates on each char of the String and checks if it's in the range you want: Commented Sep 24, 2014 at 6:41

3 Answers 3

1

You need to use lookahead for this regex:

^(?=.*?[a-zA-Z])(?=.*?[0-9])[0-9a-zA-Z]+$

RegEx Demo

Lookaheads will ensure that at least one alphabet and at least one digit is present in the input string.

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

1 Comment

Thanks a lot for all your support :)
1

You don't need to include the start and end anchors while passing your regex to matches method.

[0-9a-zA-Z]*[a-zA-Z][0-9a-zA-Z]*[0-9][0-9a-zA-Z]*|[0-9a-zA-Z]*[0-9][0-9a-zA-Z]*[A-Za-z][0-9a-zA-Z]*

Comments

1

You can use this pattern (with case insensitive option):

\A(?>[0-9]+|[A-Z]+)[A-Z0-9]+\z

The idea is to use the greediness and an atomic group to be sure that the characters matched in the group are different from the first character matched outside the group.

Note: with the matches() method, you can remove the anchors, since they are implicit.

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.