user7909426
user7909426

Reputation:

Regular Expression to also allow slash "/" with existing Regex

I am facing difficulty to allow slash "/" with an existing regex

Below is an existing Regex which allows dot and numbers:

val.match(/^[0-9]+(\.[0-9]{1,2})?$/)

I changes it to...

val.match(/^[0-9]+([./][0-9\/]{1,2})?$/)

But this one won't allow the number like 1.5/384 where both dot/period and slash simultaneously.

Can someone help me with it?

Upvotes: 1

Views: 60

Answers (2)

Paul-Etienne
Paul-Etienne

Reputation: 1018

This should do what you want :

^(\d+(?:\.\d{1,2})?\/?(?:\d+\.\d{1,2})?)$

See this Regex101.com

Edit : Corrected the fact that it didn't match 1 or 1.5

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may add an optional non-capturing group after your main pattern part to match 1 or 0 occurrences of / followed with 1 or more digits:

/^\d+(?:\.\d{1,2})?(?:\/\d+)?$/
                   ^^^^^^^^^^

See the regex demo

Details

  • ^ - start of string
  • \d+ - 1 or more digits
  • (?:\.\d{1,2})? - an optional sequence of . and then 1 or 2 digits
  • (?:\/\d+)? - an optional sequence of / and then 1+ digits
  • $ - end of string.

If the number after / can be float in the same format as the first number:

/^\d+(?:\.\d{1,2})?(?:\/\d+(?:\.\d{1,2})?)?$/
  ^^^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^^^

Upvotes: 1

Related Questions