[英]Match repeated pattern in a query string using a regex
I have a series of URL params and I need extract some of them that are repeated. 我有一系列URL参数,我需要提取其中一些重复的参数。 For example:
例如:
Required params "m" 必需参数“ m”
I have a string how this: 我有一个字符串如何:
m=123456789&reset=true&color=blue&getppm=1112&comparechars=yes&alternatem=5&.....
This repeats about 10 times with different values. 使用不同的值重复大约10次。
I have this regex: 我有这个正则表达式:
m=(.*?)&
But my problem is that other params are entering too ( getppm
, alternatem
). 但是我的问题是其他参数也正在进入(
getppm
, alternatem
)。
m
is the first in some cases. 在某些情况下,
m
是第一个。 It could vary in some cases, and I can't use &m=
in such cases. 在某些情况下可能会有所不同,在这种情况下我不能使用
&m=
。
How can I solve this problem? 我怎么解决这个问题?
EDIT: The m param normally is continued by a serie of numbers and uppercase letters on this type: 编辑:m参数通常由该类型的一系列数字和大写字母继续:
m=1A2B3C4D6D8A7D5S.32D4D1D5D3D6D8D&nextparam=...
I was trying with {x,x} variations without successfull 我尝试使用{x,x}变体而没有成功
The key to solving this is using the "word boundary" regex \\b
. 解决此问题的关键是使用“单词边界”正则表达式
\\b
。
To extract the value of the "m" parameter: 要提取“ m”参数的值:
String m = str.replaceAll(".*?\\bm=([^&]+).*", "$1");
GET parameter key-value pairs are delimited by &
(prepended by ?
for the first key-value pair in the URL). GET参数键值对以
&
分隔(URL中的第一个键值对以?
开头)。
You could simply use a lookbehind to limit the parameter to actual m
instead of [something]m
. 您可以简单地使用lookbehind将参数限制为实际的
m
而不是[something]m
。
For instance: 例如:
String params = "myUrl?m=123456789&reset=true&color=blue&getppm=1112&comparechars=yes&alternatem=5&...";
// Pattern improved as per Pschemo's suggestion
Pattern pattern = Pattern.compile("(?<=&|\\?)m=([^&?]+)");
Matcher matcher = pattern.matcher(params);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output 输出量
123456789
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.