views:

71

answers:

1

How to Specify NOT with Regular Expressions for Words

I want to filter a list of event names based on a regular expression. I can create a regular express to include (or match) name, but what would be the regular express to exclude (not match) a name?

For instance, if I want to include mouse events then the pattern would be "^Mouse". If I want all property changed events then "Changed$" is perfect. Yet, what would be the regular expression if I wanted to exclude these changed events?

Following is an example of how I plan to use the pattern.

Private _regEx As Regex

Public Sub New(ByVal pattern As String)
    'pattern = "Changed$"
    _regEx = New Regex(pattern)
End Sub

Private Function IsValid(ByVal eventName As String) As Boolean
    Return _regEx.IsMatch(eventName)
End Function

Additionally, I want to combine the patterns. For example, I want to exclude all changed and mouse events. The opposite of "^Mouse|Changed$"

+1  A: 

Just negate your return value?

Return Not oRegEx.IsMatch(eventName)

If you can only manipulate the regex itself, then you could try a negative lookahead:

^(?!regexgoeshere)

which will only match if the regex specified inside it does not match from the beginning of the input string. However, if you're trying to tail-match things, you'd either have to use a negative look-behind (not supported by all regex engines) or add the appropriate wildcards to your regex to first consume the beginning of the string:

^(?!.*Changed$)
Amber
The user of the component needs to specify the pattern. The RegEx would already be created and compiled. IsValid is only a single line function Return <code>_regEx.IsMatch(eventName)</code>.
AMissico
You could try a negative lookahead then.
Amber
YOU ARE AWESOME!
AMissico
Perfect and easy. `Dim oRegEx As New Regex("^(?!.*Changed$|^Mouse)")`
AMissico