Beginner
Beginner

Reputation: 129

How to negate a regex expression?

I am checking a string assigned to the variable s and I have this so far:

If Regex.IsMatch(s, "[\d]+") Then something
If Regex.IsMatch(s, "[A-Z]+") Then something
If Regex.IsMatch(s, "[a-z]+") Then something
If Regex.IsMatch(s, "[$%&*_=+^]+") Then something
If Regex.IsMatch(s, "^([\d]|[A-Z]|[a-z]|[$%&*-_=+^])") Then something

The problem lies with my last expression. I am trying to say, if you have anything other than a digit, uppercase, lowercase or one of my allowed symbols then do something. I have tried to use negation ^ but it isn't working. Each if statement is setting a counter so this isn't an if, else if scenario

Upvotes: 1

Views: 759

Answers (2)

Callum Watkins
Callum Watkins

Reputation: 2991

You can use a boolean to keep track of your progress through each check.

Dim matches = False
If Regex.IsMatch(s, "[\d]+") Then matches = True
If Regex.IsMatch(s, "[A-Z]+") Then matches = True
If Regex.IsMatch(s, "[a-z]+") Then matches = True
If Regex.IsMatch(s, "[$%&*_=+^]+") Then matches = True
If Not matches Then something

Then just change each statement to multiline syntax if you want to perform other operations within them rather than just checking if they match.

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25341

You don't need to negate it, simply use ElseIf for all those cases and then use Else for the last one:

If Regex.IsMatch(s, "[\d]+") Then
    'something
ElseIf Regex.IsMatch(s, "[A-Z]+") Then
    'something
ElseIf Regex.IsMatch(s, "[a-z]+") Then
    'something
ElseIf Regex.IsMatch(s, "[$%&*_=+^]+") Then
    'something
Else
    'something
End If

Upvotes: 0

Related Questions