Easy question this time.
I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^x]" where x is the character that you don't want to appear, but that doesn't seem to be working.
For example,
Regex.IsMatch("103","[^0]")
and
Regex.IsMatch("103&","[^&]")
both return true (I would expect false).
I started using "[^&]"
and thought maybe the & needed to be escaped as \&, but it didn't seem to make a difference.
Ideas? I assume it's something small.
Also, I'm using .NET, so keep that in mind.
Edit1:
I found this, but it doesn't seem to answer the issue I'm having.
Edit2:
I wanted to respond to Kevin and Joel's suggestions. These suggestions would indeed be faster, but they don't accomplish the flexibility I need in this case, so if you found this question through search, definitely look to see if their answers will fit your needs. In my case, the regular expression is getting passed in to a DataTable validation method that loops through each row and verifies that the contents of that row in a specific column matches the RegEx that is getting passed in. Since I'll be reusing this method for several other DataTables that are being validated, I wanted to:
Hopefully that helps.
$ means "Match the end of the string" (the position after the last character in the string).
Your solution is half right. The match you see is for the other characters. What you want to say is something like "hey! I do not want to see this character in the entire string".
In that case you do:
Regex.IsMatch("103","^[^0]*$")
The pattern [^0] will match any character that is not a zero. In both of your examples, the pattern will match the first character ("1"). To test whether the entire string contains no zeros, the pattern should be "^[^0]*$". This reads as follows: Start at the beginning of the string, match an arbitrary number of characters which are not zeros, followed immediately by the end of the string. Any string containing a zero will fail. Any string containing no zeros will pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With