正则表达式查找带有可选空格的字符串 [英] 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
到目前为止我在 edit=yes
上的匹配,但仅此而已.我认为我的可选空格参数是错误的,但不确定如何.
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]
推荐答案
试试这个:
edit\s?=\s?yes(once)?
正则表达式的问题:
- 空格是
\s
,而不是/s
- 转义字符是反斜杠,而不是斜杠. - 在单个字符(或转义实体)周围不需要
[]
[yes|yesonce]
表示任意一个字符y e s |y e s o n c e
,而不是yes
或yesonce
.- 您的意思是
(yes|yesonce)
,尽管它总是与yes
匹配,并且不会在yes 之后捕获
once
匹配.您可以改用(yesonce|yes)
来避免这种情况,但是.. yes(once)?
更简单 :)
- 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 eitheryes
oryesonce
.- You meant
(yes|yesonce)
, although that would always matchyes
, and not capture theonce
after theyes
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)?
这篇关于正则表达式查找带有可选空格的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文