Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex optional suffix

Tags:

regex

I'm using the following regular expression to validate CSS sizes:

([0-9]*\.?[0-9]+)(em|px|%)

The following sizes are therefore valid:

  • 10px
  • 10.2px
  • 1.5em
  • 100%

How can I change the regex to make the unit (em|px|%) optional to allow a number only?

like image 646
Ben Foster Avatar asked Nov 02 '25 11:11

Ben Foster


1 Answers

You can simply add ? at the end to make the unit optional.

([0-9]*\.?[0-9]+)(em|px|%)?

As the unit is now optional, this pattern will allow numbers only entities as well. Be aware however, that doing some will also partial match the content making the following valid.

  • 10pt
  • 10notvalid

If this is an issue, then you can add the ^ start of string and $ end of line string pattern modifiers to restrict the check.

([0-9]*\.?[0-9]+)(em|px|%)?$
like image 111
Kami Avatar answered Nov 05 '25 14:11

Kami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!