如何使正则表达式匹配查询字符串?

时间:2023-01-14 14:15:16

I'm working on a simple router, and I need to be able to identify if there's a query-like structure at the end of a URL address. What I came up with:

我正在使用一个简单的路由器,我需要能够识别URL地址末尾是否有类似查询的结构。我想出了什么:

(\?([^&=]+)=([^&=]+)&?)+$

simply does not work! It works on a first iteration: i.e. xxx?foo=bar, but definitely not on two i.e. xxx?foo=bar&greeting=hello won't work.

根本行不通!它适用于第一次迭代:即xxx?foo = bar,但绝对不是两个,即xxx?foo = bar&greeting = hello将不起作用。

What am I doing wrong? And also: Is there a better solution to accomplish this?

我究竟做错了什么?而且:有没有更好的解决方案来实现这一目标?

1 个解决方案

#1


0  

You need to match one key-value pair (([^&=]+)=([^&=]+)) preceded with a question mark (\?([^&=]+)=([^&=]+)) followed by zero to any number of key-value pairs preceded by an ampersand each ((?:&([^&=]+)=([^&=]+))*):

您需要匹配一个键值对(([^&=] +)=([^&=] +))前面带有问号(\?([^&=] +)=([^&= ] +))后跟零到任意数量的键值对,前面跟一个&符号((?:&([^&=] +)=([^&=] +))*):

\?([^&=]+)=([^&=]+)(?:&([^&=]+)=([^&=]+))*$

Demo: https://regex101.com/r/OHdRHS/1

#1


0  

You need to match one key-value pair (([^&=]+)=([^&=]+)) preceded with a question mark (\?([^&=]+)=([^&=]+)) followed by zero to any number of key-value pairs preceded by an ampersand each ((?:&([^&=]+)=([^&=]+))*):

您需要匹配一个键值对(([^&=] +)=([^&=] +))前面带有问号(\?([^&=] +)=([^&= ] +))后跟零到任意数量的键值对,前面跟一个&符号((?:&([^&=] +)=([^&=] +))*):

\?([^&=]+)=([^&=]+)(?:&([^&=]+)=([^&=]+))*$

Demo: https://regex101.com/r/OHdRHS/1