Search code examples
regexregular-language

How to write regex that can accept only numbers or fraction format?


I want to write regex that can only accept numbers or a fraction. For example:

12453  Valid
562    Valid
1142/75  Valid
65/1    Valid
1.2    Invalid
asd    Invalid
/45    Invalid

Now i wrote this for fraction

^\d+\/\d+$

It is working fine for 1/1,45/15 etc

This is for numbers only

^\d*$

Now user can write only numbers or fraction. How i make a regex that can be used in this case?


Solution

  • Now user can write only numbers or fraction. How i make a regex that can be used in this case?

    You can make fraction part optional in your regex by grouping in in an optional group.

    You can use:

    ^\d+(?:\/\d+)?$
    

    (?:\/\d+)? is optional non-capturing-group that makes fractional part optional in regex pattern.