问题
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 charactersy e s | y e s o n c e, not eitheryesoryesonce.- You meant
(yes|yesonce), although that would always matchyes, and not capture theonceafter theyeswas 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