Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"00000000000000000000000000000" matches Regex "^[1-9]|0$"

Tags:

c#

.net

regex

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.

like image 531
SubmarineX Avatar asked Sep 24 '14 07:09

SubmarineX


People also ask

What is regex class 9?

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.

What does the regular expression '[ a za z ]' match?

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.

What is the regular expression matching zero or more specific characters in UFT?

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.

What does Matches regular expression mean?

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.


1 Answers

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)$
like image 118
Robby Cornelissen Avatar answered Sep 29 '22 17:09

Robby Cornelissen