问题
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?
回答1:
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|%)?$
回答2:
Either make the whole group optional:
([0-9]*\.?[0-9]+)(em|px|%)?
or add another alternative for the empty string:
([0-9]*\.?[0-9]+)(em|px|%|)
The optional-group regex will capture undefined for number-only values, the other regex will capture the empty string "".
回答3:
If you actually want to match em OR px OR % (but optionally) you can simply use the ?:
([0-9]*\.?[0-9]+)(em|px|%)?$
edit
Now I understand the question. Also added the anchor cause of invalid matches.
来源:https://stackoverflow.com/questions/19811885/regex-optional-suffix