Reputation: 13
I am trying to create a regular expression which will validate a text. Conditions are as follows:
Must contain at least one alphanumeric character [A-Za-z0-9]
Can contain allowed special character like [@#]. This is optional.
valid text: A, A@, @A, A@a@, @@@a etc
invalid text : @, @#, a:**, A@%, AAAAAAAAA(9 characters) etc
I have tried the below regex but it is partly working:
(?=.[\w])(?=.[@#])?.*{0,8}
Upvotes: 1
Views: 265
Reputation: 36304
You can try regex like this :
public static void main(String[] args) {
String s = "aaaaaaa";
System.out.println(s.matches("(?=.*[A-Za-z0-9])[A-Za-z0-9@#]{1,7}"));
}
O/P : true
Upvotes: 0
Reputation: 174696
Use the below regex in matches
method.
"(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"
(?=.*?[A-Za-z0-9])
asserts that the string must contain atleast one letter or digit , so there must be a single character present in the match. That's why i defined [A-Za-z0-9@#]{1,8}
instead of [A-Za-z0-9@#]{0,8}
String[] check = {"A", "A@", "@A", "A@a@", "@@@a", "@", "@#", "a:**", "A@%", "AAAAAAAAA"};
for(String i: check)
{
System.out.println(i.matches("(?=.*?[A-Za-z0-9])[A-Za-z0-9@#]{1,8}"));
}
Output:
true
true
true
true
true
false
false
false
false
false
Upvotes: 0