1

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

Toto
  • 89,455
  • 62
  • 89
  • 125
mnu-nasir
  • 1,642
  • 5
  • 30
  • 62
  • Looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/a/2759417/3832970) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Nov 12 '19 at 10:35
  • Show us what you've tried. – Mitya Nov 12 '19 at 10:35
  • 1
    How about: `^\d+[.:]?\d+$` – Toto Nov 12 '19 at 11:02
  • So is `.54745` valid? – MonkeyZeus Nov 12 '19 at 14:25

3 Answers3

1

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

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
1

Try the below code. Demo is here

^([.:]\d+|\d+([.:]\d+)?)$
Karmveer Singh
  • 939
  • 5
  • 16
0

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

Toto
  • 89,455
  • 62
  • 89
  • 125