我想了解有关正则表达式的内容。
这里是我要匹配:正则表达式:查询字符串参数匹配
/parent/child
/parent/child?
/parent/child?firstparam=abc123
/parent/child?secondparam=def456
/parent/child?firstparam=abc123&secondparam=def456
/parent/child?secondparam=def456&firstparam=abc123
/parent/child?thirdparam=ghi789&secondparam=def456&firstparam=abc123
/parent/child?secondparam=def456&firstparam=abc123&thirdparam=ghi789
/parent/child?thirdparam=ghi789
/parent/child/
/parent/child/?
/parent/child/?firstparam=abc123
/parent/child/?secondparam=def456
/parent/child/?firstparam=abc123&secondparam=def456
/parent/child/?secondparam=def456&firstparam=abc123
/parent/child/?thirdparam=ghi789&secondparam=def456&firstparam=abc123
/parent/child/?secondparam=def456&firstparam=abc123&thirdparam=ghi789
/parent/child/?thirdparam=ghi789
我的表情应该 “待价而沽” ABC123和def456。
而现在只是什么我不打算匹配的例子(“问号”丢失):
/parent/child/firstparam=abc123&secondparam=def456
好吧,我建立了下面的表达式:
^(?:/parent/child){1}(?:^(?:/\?|\?)+(?:firstparam=([^&]*)|secondparam=([^&]*)|[^&]*)?)?
但是,没有按没有工作。
你能帮我理解我做错了什么吗?
在此先感谢。
更新1
好吧,我做其他检查。 我想用这样的修复以前版本:
/parent/child(?:(?:\?|/\?)+(?:firstparam=([^&]*)|secondparam=([^&]*)|[^&]*)?)?$
让我解释一下我的想法:
必须与/父母/子女开始:
/parent/child
下面的一组是可选的
(?: ...)?
上一个可选组必须以?开头?要么 /?
(?:\?|/\?)+
可选参数(I抢值如果指定的参数是查询字符串的一部分)线
$
任何建议的
(?:firstparam=([^&]*)|secondparam=([^&]*)|[^&]*)?
结束?
更新2
我的解决方案必须基于刚上正则表达式。 就比如,我以前写了下面的一个:
/parent/child(?:[?&/]*(?:firstparam=([^&]*)|secondparam=([^&]*)|[^&]*))*$
这工作相当不错。 但它下面的输入也很相配:
/parent/child/firstparam=abc123&secondparam=def456
我怎么能修改表达式以不以前的字符串相匹配?
这是你所有可能的输入吗?它总是有这样的结构吗? – FailedDev 2012-08-02 08:20:24
@FailedDev 是的。 – NicolaBaldi 2012-08-02 08:46:10
@NicolaBaldi看到我的答案。不要为此使用正则表达式,导致类似你的任务可以(并且必须)通过简单的字符串处理函数来解决;)正则表达式是昂贵的工具,真的! – gaussblurinc 2012-08-02 10:32:02