mnu-nasir
mnu-nasir

Reputation: 1760

Regular expression for validate number with or without colon or decimal point

I would like to write a regular expression which allow only numbers and decimal point or colon (:) instead of decimal point. Bellow is some example

Valid:

87887
8787.878
8878:98

Invalid

abc
989ab
8987.89:87

I have the regular expression ^[0-9.:]+$ to validate but its accepts colon after the decimal point . which means if I write 898.:89, it shows valid.

Can you please help me to find out a solution

Upvotes: 1

Views: 541

Answers (3)

Toto
Toto

Reputation: 91385

You can use:

^\d+[.:]?\d+$

Demo & explanation

update:

If you also want to match .1 you should use:

^\d*[.:]?\d+$

If you also want to match 1. you should use:

^\d+[.:]?\d*$

If you want to match all combinations, like .1, 1. and 12.34 you should use:

^(?=.*\d)\d*[.:]?\d*$

Demo & explanation

Upvotes: 0

Karmveer Singh
Karmveer Singh

Reputation: 953

Try the below code. Demo is here

^([.:]\d+|\d+([.:]\d+)?)$

Upvotes: 2

MonkeyZeus
MonkeyZeus

Reputation: 20737

This would work:

^(?:[0-9]+(?:[.:][0-9]+)?|[.:][0-9]+)$
  • ^ - start string anchor
  • (?: - start non-capturing group so that the start and end anchors are global instead of becoming part of the or clause
  • [0-9]+ - allow digits
  • (?:[.:][0-9]+)? - optionally allow a colon or period which must be follow by at least one digit
  • | - or
  • [.:][0-9]+ - colon or period followed by a digit
  • ) - close capture group
  • $ - end string anchor

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

Upvotes: 1

Related Questions