RegEx to tell if a string does not contain a specific character

匆匆过客 提交于 2019-12-03 02:04:05

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 are looking for a single character in a string, regex seems like a bit of an overkill. Why not just use .IndexOf or .Contains ?

The first character the parser reaches is "1", which is true for [^0] and also true for [^&], so therefore it will return true in both of those examples.

You're putting your negation in the wrong place. [^x] will match anything that isn't x. If x is in the string, the string still matches the expression if there are any other characters as well. Instead, you want to match true if x is there, and then negate the result of the function:

Not Regex.IsMatch("103", "0")

Not Regex.IsMatch("103&", "&")

Not that with these simple examples, the normal String.IndexOf() or String.Contains() would be a better choice.

Brett

I came across this question looking for the same thing but for JavaScript. The expression above did not work in my case, but I came across the below expression which did. (Just in case anybody else looking for a JavaScript solution ends up here too.)

^((?!0).)*$

This construct is called a Negative Lookahead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!