In .Net4.5, I find that the result of
System.Text.RegularExpressions.Regex.IsMatch(
"00000000000000000000000000000", "^[1-9]|0$")
is true.
The result I expect is false. I don't know why. Can you help me?
Update:
In the beginning, I was validating the regular expression ^-?[1-9]\d*|0$
which is used to match integer found on the internet and I find that the string with multiple 0
matches the regular expression.
A regular expression, also known as regex, is a pattern that represents a collection of strings that match the pattern. To put it another way, a regex only accepts a specific set of strings while rejecting all others.
For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.
Matching Zero or More Specific Characters ( * )An asterisk (*) instructs UFT One to match zero or more occurrences of the preceding character. For example, ca*r matches car, caaaaaar, and cr.
In regular expression syntax the period . mean "match any character" and the asterisk * means "any number of times". So it basically means match anything (even an empty string). It shouldn't filter out anything.
The issue is the alternator's binding behavior. By default (i.e. without using grouping), an expression containing an alternator (|
) will match either the value to the left of the alternator, or the value to the right.
So in your expression, you're matching either one of these:
^[1-9]
0$
Your call to the IsMatch
method returns true
because the second of those two option matches the string 00000000000000000000000000000
.
To restrict the alternator's binding to a specific part of your expression, you need to group using parentheses, as follows:
^([1-9]|0)$
Putting all this together, a strict expression to validate integers, disallowing leading zeroes and negative zero, could look like this:
^(-?[1-9][0-9]*|0)$
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