3

I am trying to validate dot and numbers.

Valid:

1.2.3 1.4.1 

Invalid:

1.2.3. 1.2-3 1-2-3 

I tried the following from another thread, it works with the valid, but it also passes the invalid with dash (-).

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

Any betterment to the regex so it strict to validate only dot and digit?

Thanks

5 Answers 5

4

You need to escape the dot, which is otherwise "any character" in a regex:

^\d+(\.\d+)*$ 
Sign up to request clarification or add additional context in comments.

Comments

3

Ttry this:

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

Regex Demo

Comments

2

If you need a variable number of dots and digits repeat digits & dots and put the last as only digit:

(\d+\.)+\d+ 

it matches 1.2.3 1.2.3.4 and so on

If you need fixed length of digits put the number of repetitions instead of the + operator

(\d+\.){2}\d+ #for 1.2.3 (\d+\.){1}\d+ #for 1.2 

1 Comment

Thanks a lot, I really appreciate it. Good lesson.
1

use this regular expression ^\d+\.\d+\.\d+$

your misstake in dot, dot mean any symbol

Comments

1

The dot matches all characters, you should use \.

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

But this would also validate any number without dot, when at least 1 dot should be present use:

(\d+\.)+\d+

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.