Craig Beamson
asked on
Using RegEx to specify what NOT to match (ASP.NET / VB)
Instead of using regex to remove matched patterns, I'd prefer to use it to remove unmatched patterns. Can this be done? I have a few scenarios where I want to exclude characters where its easier to define what not to match than than the other way round.
Example:
strTest="This sentance con^&*tains 3 characters that I would like to replace"
objRegEx = New RegEx("[a-zA-Z0-9 ]")
Return UCase(objRegEx.Replace( strTest, "" ))
This will return "^&*"
What I want to return is "This sentance contains 3 characters that I would like to replace"
I'd want to use regex to replace all characters that are NOT (alpha characters, numeric characters OR spaces).
I need a specific solution to the above problem but could also do with a generic way of specifying what patterns are NOT to be matched.
Example:
strTest="This sentance con^&*tains 3 characters that I would like to replace"
objRegEx = New RegEx("[a-zA-Z0-9 ]")
Return UCase(objRegEx.Replace( strTest, "" ))
This will return "^&*"
What I want to return is "This sentance contains 3 characters that I would like to replace"
I'd want to use regex to replace all characters that are NOT (alpha characters, numeric characters OR spaces).
I need a specific solution to the above problem but could also do with a generic way of specifying what patterns are NOT to be matched.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Exactly what I needed to know - thanks.
NP.
?i[^A-Z\d ]
?i means caseless, so a-z AND A-Z are the same.
[] means the "set of"
^ means NOT
a-z
\d means 0-9
So this says match anything that is NOT a-z, A-Z, 0-9 or a space.