0

I have a series of URL params and I need extract some of them that are repeated. For example:

Required params "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.

I have this regex:

m=(.*?)&

But my problem is that other params are entering too (getppm, alternatem).

m is the first in some cases. It could vary in some cases, and I can't use &m= in such cases.

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=1A2B3C4D6D8A7D5S.32D4D1D5D3D6D8D&nextparam=...

I was trying with {x,x} variations without successfull

3
  • Isn't m always preceded by some specific character? Define "vary in some cases"! Commented Jun 29, 2014 at 14:10
  • Difficult to understand logic of repeating pattern here. Commented Jun 29, 2014 at 14:17
  • Sometimes m is preceded by &, others by ", others by blank space, others by comma,.... its difficult because this varies. Commented Jun 29, 2014 at 14:22

2 Answers 2

2

The key to solving this is using the "word boundary" regex \b.

To extract the value of the "m" parameter:

String m = str.replaceAll(".*?\\bm=([^&]+).*", "$1");
Sign up to request clarification or add additional context in comments.

Comments

1

GET parameter key-value pairs are delimited by & (prepended by ? for the first key-value pair in the URL).

You could simply use a lookbehind to limit the parameter to actual m instead of [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

1 Comment

Maybe instead of .+? consider using [^&?]+. This way you wouldn't need to check (.+?)(?=&|\\?) conditions - which probably should also contain end of string $ if m=... would be last parameter).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.