我有
String content= "<a data-hovercard=\"/ajax/hovercard/group.php?id=180552688740185\">
<a data-hovercard=\"/ajax/hovercard/group.php?id=21392174\">"
我想获取 "group.php?id="
和 "\""
之间的所有 id
例如:180552688740185
这是我的代码:
String content1 = "";
Pattern script1 = Pattern.compile("group.php?id=.*?\"");
Matcher mscript1 = script1.matcher(content);
while (mscript1.find()) {
content1 += mscript1.group() + "\n";
}
但由于某种原因它不起作用。
你能给我一些建议吗?
最佳答案
为什么使用.*?
来匹配id
。 .*?
将匹配每个字符。您只需要检查数字
。因此,只需使用 \\d
即可。
此外,您需要捕获 id
然后打印它。
// 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
}
关于java - 如何使用模式匹配获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12898211/