简体   繁体   中英

Regex to find string with optional spaces

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]

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 yes | yesonce yes | yesonce , 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)?

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

this will assure that :

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

You can use this regex, your slashes were reversed:

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

Test cases here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM