<tr><th align=right>现有数量</th>
<td id=quantityavailable align=left><span itemprop="offers" itemscope itemtype="http://schema.org/Offer"><link itemprop="availability" href="http://schema.org/InStock" /></span>Digi-Key库存现货
: 6,000<br>可立即发货
</td></tr>想用JAVA正则,提取出现货数量 也就是 6000 怎么提取了
自己写了一段。但是没结果 String pp="<td\\s*id=quantityavailable align=left><span itemprop=\"offers\" itemscope itemtype=\"(.*?)\">\\s*"; pp+="<link itemprop=\"availability\" href=\"(.*?)\" /></span>Digi-Key库存现货\\s*";
pp+=": ([0-9\\,]+)\\s*<br>"; Pattern p = Pattern.compile(pp); Matcher m = p.matcher(x);
while (m.find()) { System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println();
}
提取不到结果。
<td id=quantityavailable align=left><span itemprop="offers" itemscope itemtype="http://schema.org/Offer"><link itemprop="availability" href="http://schema.org/InStock" /></span>Digi-Key库存现货
: 6,000<br>可立即发货
</td></tr>想用JAVA正则,提取出现货数量 也就是 6000 怎么提取了
自己写了一段。但是没结果 String pp="<td\\s*id=quantityavailable align=left><span itemprop=\"offers\" itemscope itemtype=\"(.*?)\">\\s*"; pp+="<link itemprop=\"availability\" href=\"(.*?)\" /></span>Digi-Key库存现货\\s*";
pp+=": ([0-9\\,]+)\\s*<br>"; Pattern p = Pattern.compile(pp); Matcher m = p.matcher(x);
while (m.find()) { System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println();
}
提取不到结果。
另外正则不推荐大量使用.*?,这样降低效率。
我是否可以以这个“Digi-Key库存现货”为提取标志呢?
String regex="Digi-Key库存现货\\d{1,}"
简单写了一下,String s="Digi-Key库存现货6000<br>";
Pattern p=Pattern.compile("(?s)Digi-Key库存现货(\\d{1,}).*?");
Matcher m=p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
Matcher m = p.matcher(x);
while (m.find()) { System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println();
}另外。我是要匹配 Digi-Key库存现货
: 6,000 这个里面的哦。哪个冒号是中文下的。
public class GetNumber
{ public static void main(String[] args)
{
//原始字符串
String html =
"<tr><th align=right>现有数量</th>" + "<td id=quantityavailable align=left>"
+ "< span itemprop=\"offers\" itemscope itemtype=\"http://schema.org/Offer\">"
+ "<link itemprop=\"availability\" href=\"http://schema.org/InStock\" />"
+ "</span>Digi-Key库存现货: 6,000<br>可立即发货</td></tr>"; String number = "";
//初步分割
if (html.contains("Digi-Key库存现货:"))
{
String onceSubStr = html.split("Digi-Key库存现货:")[1]; //再次分隔
if (onceSubStr.contains("<br>"))
{
String twiceStr = onceSubStr.substring(0, onceSubStr.indexOf("<br>"));
//去空格和逗号
number = (twiceStr.replaceAll("\\s", "")).replaceAll(",", "");
}
} //没找到数量
if ("".equals(number))
{
System.out.println("库存现货数量不存在。");
}
else
{
System.out.println("Digi-Key库存现货:" + number);
}
}
}