Regex optional suffix

时光总嘲笑我的痴心妄想 提交于 2021-01-27 17:55:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!