EkoostikMartin
EkoostikMartin

Reputation: 6921

RegEx for limited decimal

New to regex syntax here. Trying to write a regex to provide some input validation.

What I need is a regex to match a whole number, or a decimal with exactly one digit past the decimal.

Good Match
1
12
100
1.1
100.1
1.0

No Match
1.22
1.
0
012

Here is what I came up with but it doesn't work:

Regex.IsMatch(paidHours, "\\d+[.]?[0-9]?")

Upvotes: 1

Views: 444

Answers (4)

Otiel
Otiel

Reputation: 18743

Edited answer after OP question edit.

Regex.IsMatch(paidHours, @"^[1-9][0-9]*(\.[0-9])?$");

Explanation:

^      : Start of the String
[1-9]  : A single number between 1 and 9
[0-9]* : Zero or more number(s) between 0 and 9 
         ([0-9]? would match zero or one number and the String "100" would not match the regex)
(      : Start of a group
\.     : A point
[0-9]  : A single number between 0 and 9
)?     : End of the group. The group must be repeated zero or one time
$      : End of the String

Please note that \d is not exactly equivalent to [0-9]: \d matches any unicode digit. For instance, this character will be matched if you use \d but won't be if you use [0-9].

Upvotes: 2

Felice Pollano
Felice Pollano

Reputation: 33272

Try to specify beggining/end of the line:

@"^\d+[.]?[0-9]?$"

You regex won't work since ie 1.234 was a match wit 1.2, if you don't specify you want the string ends with the '$' sign.

Upvotes: 0

Ruel
Ruel

Reputation: 15780

Regex.IsMatch(paidHours, @"^\d+(\.\d)?$")

Upvotes: 3

hsz
hsz

Reputation: 152294

You can try with:

Regex.IsMatch(paidHours, "^\\d+(\\.\\d)?$")

Upvotes: 3

Related Questions