FireWings
FireWings

Reputation: 13

Regular expression of validating text which contains certain special characters on condition

I am trying to create a regular expression which will validate a text. Conditions are as follows:

  1. Must contain at least one alphanumeric character [A-Za-z0-9]

  2. Can contain allowed special character like [@#]. This is optional.

  3. No other characters are allowed other than the above mentioned chars[includes @ and #].
  4. Text length should be less than 8.

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

Answers (4)

TheLostMind
TheLostMind

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

Avinash Raj
Avinash Raj

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

vks
vks

Reputation: 67968

^(?=.*[a-zA-Z0-9])[A-Za-z0-9@#]{0,8}$

Try this.See demo.

The lookahead will make sure there is atleast one character.

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You can use:

^(?=.*?[A-Za-z0-9])[@#A-Za-z0-9]{1,8}$

Upvotes: 0

Related Questions