Deko
Deko

Reputation: 71

Regex - I need to include non-alphabetic character

i have this expression and i need to make sure to include at least one non-alphabetic character

^(?!.*(.)\1)\S{8,12}$

Upvotes: 0

Views: 110

Answers (3)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

It's better to do it with separate if-statements. This way you'll have exact information what is missing in the value. With regexps you'll only get a true/false result if the value matched the pattern or not - you'll have no information WHAT is missing in the value.

For example:

if(!value.Any(c => !char.IsLetter(c)){
    throw new Exception("value must contain at least one non-letter")
}

Upvotes: 0

TeWu
TeWu

Reputation: 6536

You can just check for the special character (as matched by [\p{P}\p{S}]) in positive lookahead (?=.*[\p{P}\p{S}]), which gives you the regex:

^(?!.*(.)\1)(?=.*[\p{P}\p{S}])\S{8,12}$

See online demo

You can also replace [\p{P}\p{S}] by [!"\#$%&'()*+,\-./:;<=>?@\[\\\]^_‘{|}~], or any other character set that list all the characters that you want to count as being "special characters".

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163287

You could use a positive lookahead asserting at least 1 char other than a-zA-Z

^(?!.*(.)\1)(?=.*[^\sa-zA-Z])\S{8,12}$

Explanation

  • ^ Start of string
  • (?!.*(.)\1) Assert not 2 consecutive chars
  • (?=.*[^\sa-zA-Z]) Assert 1 char other than a whitespace char and a-zA-Z
  • \S{8,12} Match 8-12 non whitespace chars
  • $ End of string

Regex demo

Another option is to use \P{L} to assert any char other than any kind of letter from any language

^(?!.*(.)\1)(?=.*\P{L})\S{8,12}$

Regex demo

Upvotes: 2

Related Questions