Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Regular expression which check length and non-alphanumeric characters

Tags:

c#

.net

regex

I need Regexp to validate string has minimum length 6 and it is contains at least one non-alphanumeric character e.g: "eN%{S$u)", "h9YI!>4j", "{9YI!;4j", "eN%{S$usdf)", "dfh9YI!>4j", "ghffg{9YI!;4j".

This one is working well ^.*(?=.{6,})(?=.*\\d).*$" but in cases when string does not contain any numbers(e.g "eN%{S$u)") it is not working.

like image 273
Reg Avatar asked Jan 08 '11 06:01

Reg


People also ask

How do you check if a character is alphanumeric or not?

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space)!

How do I find the length of a string in regex?

To check the length of a string, a simple approach is to test against a regular expression that starts at the very beginning with a ^ and includes every character until the end by finishing with a $.


2 Answers

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

We use positive lookahead to assure there are at least 6 characters. Then we match the pattern that looks for at least one non-alphanumeric character ([^0-9a-zA-Z]). The .*'s match any number of any characters around this one non-alphanumeric character, but by the time we've reached here we've already checked that we're matching at least 6.

^.*(?=.{6,})(?=.*\\d).*$"

is the regex you tried. Here are some suggestions:

  • You don't need to match more than 6 characters in the lookahead. Matching only 6 here does no restrict the rest of the regular expression from matching more than 6.
  • \d matches a digit, and (?=.*\\d) is a lookahead for one of them. This is why you are experiencing the problems you mentioned with strings like eN%{S$u).
  • Even if the point above wasn't incorrect and the regular expression here was correct, you can combine the second lookahead with the .* that follows by just using .*\\d.*.
like image 146
moinudin Avatar answered Sep 21 '22 11:09

moinudin


marcog's answer is pretty good, but I'd do it the other way around so that it's easier to add even more conditions (such as having at least one digit or whatever), and I'd use lazy quantifiers because they are cheaper for certain patterns:

^(?=.*?[^0-9a-zA-Z]).{6}

So if you were to add the mentioned additional condition, it would be like this:

^(?=.*?[^0-9a-zA-Z])(?=.*?[0-9]).{6}

As you can see, this pattern is easily extensible. Note that is is designed to be used for checking matches only, its capture is not useful.

like image 31
Lucero Avatar answered Sep 22 '22 11:09

Lucero