Reputation: 7953
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
Upvotes: 1
Views: 1242
Reputation: 89557
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.
Upvotes: 1
Reputation: 174696
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]*
Upvotes: 1
Reputation: 785058
You need to use lookahead for this regex:
^(?=.*?[a-zA-Z])(?=.*?[0-9])[0-9a-zA-Z]+$
Lookaheads
will ensure that at least one alphabet and at least one digit is present in the input string.
Upvotes: 1