Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise regular expression to accomplish this task?

Tags:

regex

vb.net

First off, sorry for the lame title, but I couldn't think of a better one. I need to test a password to ensure the following:

Passwords must contain at least 3 of the following:

  • upper case letters
  • lower case letters
  • numbers
  • special characters

Here's what I've come up with (it works, but I'm wondering if there is a better way to do this):

    Dim lowerCase As New Regex("[a-z]")
    Dim upperCase As New Regex("[A-Z]")
    Dim numbers As New Regex("\d")
    Dim special As New Regex("[\\\.\+\*\?\^\$\[\]\(\)\|\{\}\/\'\#]")

    Dim count As Int16 = 0

    If Not lowerCase.IsMatch(txtUpdatepass.Text) Then
        count += 1
    End If
    If Not upperCase.IsMatch(txtUpdatepass.Text) Then
        count += 1
    End If
    If Not numbers.IsMatch(txtUpdatepass.Text) Then
        count += 1
    End If
    If Not special.IsMatch(txtUpdatepass.Text) Then
        count += 1
    End If

If at least 3 of the criteria have not been met, I handle it. I'm not well versed in regular expressions and have been reading numerous tutorials on the web. Is there a way to combine all 4 regexes into one? But I guess doing that would not allow me to check if at least 3 of the criteria are met.

On a side note, is there a site that has an exhaustive list of all characters that would need to be escaped in the regex (those that have special meaning - eg. $, ^, etc.)?

As always, TIA. I can't express enough how awesome I think this site is.

like image 361
Matt M Avatar asked May 28 '10 13:05

Matt M


1 Answers

The way you have it is about as good as it can get. You could accomplish this all in one line, but it would be terribly obfuscated and wouldn't really help at all.

Think about what you're trying to do; you want to check for four different criteria. Since each criterion is essentially a single comparison, you'll want to check for each one individually, which is what you're doing.

like image 144
eykanal Avatar answered Oct 03 '22 09:10

eykanal