首先,我知道我的问题可能与this one重复,但我需要100%必须正确的解决方案。而且我在正则表达方面做得不太好:)
我有maaaaaaaaany请求,只有...¶ms=key1=value1|key2=value2|...
传递了几个参数。可能很少有参数,我不知道订单。我需要的是捕获包含完全key1=myValue1
和key2=myValue2
的请求,但它们可以是:
key1=myValue1|key2=myValue2
key2=myValue2|key1=myValue1
key1=myValue1|key3=myValue3|key2=myValue2
甚至更复杂。众所周知:
params
只是请求的一部分,因此可以是?something=other¶ms=key1=value1|key2=value2
或?params=key1=value1|key2=value2&something=other
params
参数内,没有白色字符,只有key=value
的对(以|
分隔)要明确:我知道两对key = value,因此regex仅用于匹配包含这两对的请求。请求可以以不同的方式订购。我没有访问请求本身,我只处理保存的数据(作为字符串)。
将使用正则表达式的语言是PHP。但我无法访问完整代码,因为我们在Web应用程序界面中声明了正则表达式。
我认为我需要两个积极的前瞻,比如(?=[^\s]*(key1=myValue1)[^\s]*){1}(?=[^\s]*(key2=myValue2)[^\s]*){1}
,但我无法让它工作,时钟正在滴答作响......
答案 0 :(得分:2)
使用两个前瞻:
^(?=.*\bkey1=myValue1\b)(?=.*\bkey2=myValue2\b)
\b
字边界锚点确保只匹配整个字母数字“单词”。
答案 1 :(得分:1)
这是针对您的特定问题的精心定制的正则表达式。 See a live demo here.
(?:^\?|&)params=(?:|[^&]*\|)([^=]+)=([^|&]*)(?=[^&]*\|\1=\2(?:[|&]|$))
| | | | | | | |
| | | | | | | Ensure the value
| | | | | | | is followed by a
| | | | | | | '|' or '&' or the
| | | | | | | end-of-string so
| | | | | | | as not to match
| | | | | | | a substring.
| | | | | | |
| | | | | | Use backreferences to
| | | | | | refer to the preceding
| | | | | | key/value pair found.
| | | | | |
| | | | | Logically it must be
| | | | | true that the second
| | | | | pair follows a '|'.
| | | | |
| | | | Keep searching for the
| | | | duplicate key/value pair as
| | | | long as we don't hit a '&'.
| | | |
| | | Consider all characters valid for a
| | | value until we hit a '|' or '&'. Also,
| | | allow empty values (*).
| | |
| | Consider all characters valid for a key until we
| | hit a '='. Therefore, expect having an odd
| | number of key/value entities to cause a problem.
| |
| Start searching immediately following the "params=" or after
| a string of non-'&' characters followed by a '|'.
|
Start at the beginning of the string with a '?', or somewhere (anywhere) in
the string with a '&'.
它优于其他解决方案的优势包括更严格地查找完整的密钥(而不是子串),当然,不需要通过反向引用来指定特定的密钥。
注意:
\r\n
仅用于演示目的。value1=key1
可能与key1=value1
偶然匹配。答案 2 :(得分:0)
这适合吗?
(key[\d]+=[^|]+)
在不知道您选择的语言的情况下,我无法提供使用它来提取组的方法。
这意味着以下内容:
Match "key" explicitly
Match any amount of numbers until you hit a non-number
Match "=" explicitly
Match any amount of characters that aren't a pipe "|"
这将匹配由管道符号分隔的任何数量的键#=值对。
编辑:回应你的评论:
([A-Za-z\d]+=[^|]+)
这意味着:
Match any amount of alphabetical characters or numbers
Match "=" explicitly
Match any character that is not a pipe character "|"
这将符合以下任何一项:
key=value|myKey=MyValue|key2012=MyValue2012|country=usa|sex=female