Reputation: 1760
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
Reputation: 91385
You can use:
^\d+[.:]?\d+$
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*$
Upvotes: 0
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 anchorhttps://regex101.com/r/Joe8oi/1
Upvotes: 1