I am learning regular expressions and I am trying to create one that will validation either a whole number or a decimal.
I have created this regular expression:
^(\d+)|([\d+][\.{1}][\d+])$
It almost works, but it says a number like:
12.
12..
12..67
are matches.
I thought
([\d+][\.{1}][\d+])
meant it had to have one or more numbers, followed by a dot (and only one), followed by one or more numbers.
Can someone explain what I am doing wrong?
As a learning process I’m interested in what I am doing wrong rather than what is another way of doing it. I tried following the syntax examples but I have missed something.
You are wrong
with the square brackets are you creating character classes. that means
[\d+]does mean match a digit or a+once.[\.{1}]does mean match a.or a{or a1or a}To get the behaviour you expect remove the square brackets
This will match at least one digit, a
.followed by one or more digitsThe other problem here is the
^belongs only to the first part of your expression and the$belong only to the last part of your alternation. So you should put brackets around the complete alternationIf you don’t need the match in a capturing group you can remove the brackets around the single alternatives
As last point as Jens noted
{1}is redundant\.{1}is the same than\.Then we are at