MarkS
MarkS

Reputation: 1539

match period followed by digit zero to 2 times

I am trying to write a regex that will match all of these:

1.5
2
2.7
3
3.5
3.5.0
3.6
4

My regex is failing to grab the 3.5.0 entry. Regex101 shows it missing the second '.', but it does grab the '0'.

I am using: (\d[\.\d]{0,2})

I guess I am failing to execute: a period followed by a single digit, repeated 0-2 times.

The full regex should be match a single digit, followed by a period followed by a single digit, repeated 0-2 times.

Upvotes: 1

Views: 1968

Answers (2)

blhsing
blhsing

Reputation: 106946

Characters in a pair of square brackets, known as a character set, matches just one character. You should enclose \.\d in parentheses instead of square brackets to actually group them as a sub-pattern for the following quantifier to repeat on.

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20747

You can use:

^\d(?:\.\d){0,2}$

https://regex101.com/r/VOXYko/1

Upvotes: 2

Related Questions