Regex to find string with optional spaces

纵然是瞬间 提交于 2021-02-05 09:23:27

问题


I'm trying to validate that a string has the values

edit=yes
edit = yes
edit= yes
edit =yes
edit=yesonce
edit = yesonce
edit= yesonce
edit =yesonce

What I have so far matches on edit=yes but nothing more. I think my optional spaces arguments are wrong but not sure how.

edit[/s]?=[/s]?[yes|yesonce]

回答1:


Try this:

edit\s?=\s?yes(once)?

Problems with your regex:

  • Whitespace is \s, not /s - the escape character is backslash, not slash.
  • You don't need [] around a single character (or escaped entity)
  • [yes|yesonce] means any one of the characters y e s | y e s o n c e, not either yes or yesonce.
  • You meant (yes|yesonce), although that would always match yes, and not capture the once after the yes was matched. You could use (yesonce|yes) instead to avoid this, but..
  • yes(once)? is simpler :)

If you intended to allow any number of spaces, rather than one or none, you need to replace the appropriate ? symbols ("zero or one") with * ("any number including zero"):

edit\s*=\s*yes(once)?



回答2:


Try this regex : /edit\s*=\s*(yes|yesonce)/ig

this will assure that :

  • edit word
  • whitespaces or not
  • =
  • whitespaces or not *yes word



回答3:


You can use this regex, your slashes were reversed:

(edit[\s]?=[\s]?[yes|yesonce]+)

Test cases here



来源:https://stackoverflow.com/questions/27260012/regex-to-find-string-with-optional-spaces

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