Bex
Bex

Reputation: 4928

Number Regular Expression Help

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.

Upvotes: 2

Views: 167

Answers (3)

stema
stema

Reputation: 93056

You are wrong

([\d+][\.{1}][\d+])

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 a 1 or a }

To get the behaviour you expect remove the square brackets

(\d+\.{1}\d+)

This will match at least one digit, a . followed by one or more digits

The 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 alternation

^((\d+)|(\d+\.{1}\d+))$

If you don't need the match in a capturing group you can remove the brackets around the single alternatives

^(\d+|\d+\.{1}\d+)$

As last point as Jens noted

{1} is redundant \.{1} is the same than \.

Then we are at

^(\d+|\d+\.\d+)$

Upvotes: 3

ipr101
ipr101

Reputation: 24236

Your regex is nearly there, you just need to remove the square brackets -

^(\d+)|(\d+\.{1}\d+)$

Should work for what you want.

Upvotes: 0

hsz
hsz

Reputation: 152304

You can try with:

^(\d+(\.\d+)?)$

Upvotes: 0

Related Questions