我有一堆共享以下模式的网址:
http://www.ebay.com/itm/Crosman-Pumpmaster-760-Pump-177-Pellet-4-5-mm-BB-Air-Rifle-Black-760B-/251635693266?pt=LH_DefaultDomain_0&hash=item3a96a7f6d2
我想提取item3a96a7f6d2
。 http://www.ebay.com/itm/
和 &hash=
是固定模式,而其间的字符串可以更改。我写道:
String prodPatternString = "(http://www.ebay.com/itm/)(.*?)(hash=)(.*?)";
Pattern prodPattern = Pattern.compile(prodPatternString);
Matcher prodMatcher = prodPattern.matcher(prodUrl);
while(prodMatcher.find()){
String pid = matcher.group(4);
}
但它给了我一个错误,说“找不到匹配项”。任何帮助将不胜感激。谢谢。
最佳答案
您需要将 matcher.group(4);
行更改为 prodMatcher.group(4);
,然后删除 ?
存在在最后一个捕获组内,因为 .*?
将对零个或多个字符进行非贪婪匹配,因此即使存在字符,它也会匹配空字符串,因为它是非贪婪形式。
String prodUrl = "http://www.ebay.com/itm/Crosman-Pumpmaster-760-Pump-177-Pellet-4-5-mm-BB-Air-Rifle-Black-760B-/251635693266?pt=LH_DefaultDomain_0&hash=item3a96a7f6d2";
String prodPatternString = "(http://www.ebay.com/itm/)(.*?)(hash=)(.*)";
Pattern prodPattern = Pattern.compile(prodPatternString);
Matcher prodMatcher = prodPattern.matcher(prodUrl);
while(prodMatcher.find()){
String pid = prodMatcher.group(4);
System.out.println(pid);
}
输出:
item3a96a7f6d2
关于Java正则表达式匹配url中的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569133/