Hiriji Sakumo
Hiriji Sakumo

Reputation: 11

How to take a substring using pattern match

I have

String content= "<a data-hovercard=\"/ajax/hovercard/group.php?id=180552688740185\">
                 <a data-hovercard=\"/ajax/hovercard/group.php?id=21392174\">"

I want to get all the id between "group.php?id=" and "\""

Ex:180552688740185

Here is my code:

String content1 = "";
Pattern script1 = Pattern.compile("group.php?id=.*?\"");
Matcher mscript1 = script1.matcher(content);
while (mscript1.find()) {
    content1 += mscript1.group() + "\n";
}

But for some reason it does not work.

Can you give me some advice?

Upvotes: 0

Views: 317

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213203

Why are you using .*? to match the id. .*? will match every character. You just need to check for digits. So, just use \\d.

Also, you need to capture the id and then print it.

// To consider special characters as literals
String str = Pattern.quote("group.php?id=") + "(\\d*)";

Pattern script1 = Pattern.compile(str);
// Your matcher line
while (mscript1.find()) {
    content += mscript1.group(1) + "\n";   // Capture group 1 contains your id
}

Upvotes: 2

Related Questions