Home > other >  RegEx Pattern - accepting what shouldn't be accepted
RegEx Pattern - accepting what shouldn't be accepted

Time:04-03

I know the Title "regex pattern does not work" links to many existing question within Stackoverflow. But I did not find a solution for my issue.

I currently work with the following pattern:

^[0-9]$|^[0-9] [\\.][^\\,][0-9]*$

so far so good a friend of mine started explorative testing. We found out that entering the value: 23.a would be accepted. And that should not be the case!

For some reason you can enter everything after the dot. as soon as you enter 23.aa or 23.!a or what ever regex works again.

So in short: User can enter value 23.a User can't enter 23.aa

it is strange and I don't understand what's wrong.

thanks for helping.

p.s. Requirement of my regex:

accepting only numeric values or values whit two digits after the dot. no commas or other characters allowed.

23 => 0k
23.1 => ok
23.02 =>
0. = nok
.0 = nok
0, = nok
,0 = nok

etc...

CodePudding user response:

"\\d (\\.\\d{1,2})?"

allows for one or two digits after a decimal point or only an integral number

CodePudding user response:

var pattern = @"^\d $|^\d \.\d{1,2}$"

Please check this pattern also. Note that it is C# verbatim string (string constants that starts with @ to escape all special characters). The generated output matches with your test.

23. =>  False
23 =>  True
23.1 =>  True
23.02 =>  True
0. =>  False
.0 =>  False
0, =>  False
,0 =>  False
23, =>  False
  • Related