嗨我正在做一個價格檢查器,從超市網站返回最便宜的項目名稱和價格。 代碼中的大多數價格是格式...價格:3.14 ...但一些價格只是簡單的...價格:2 ...正則表達式不會找到所有需要的項目
這是網站的例子搜索已進入,查看源代碼,如果你想 http://www.tesco.ie/groceries/product/search/default.aspx?searchBox=ham
我的正則表達式,我通常拿起從源代碼18/20項目,但,當它擊中只有1位數的價格ArrayList中變得不同步。
我的問題是我如何獲得正則表達式來獲取這兩種類型,並將它們添加到arraylist以保持同步。
下面是獲取價格正則表達式
字符串priceFinder = 「價格:(\ d {1,3})(\ d {1,2}。)」;
這裏是更多的代碼,如果有幫助
public static Product addProducts(String item) throws Exception {
//@SuppressWarnings("resource")
productList.clear();
item = checkCommonItems(item);
item = item.replaceAll("\\s+", "%20");
URL oracle = new URL("http://www.tesco.ie/groceries/product/search/default.aspx?searchBox="+item);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
String name, price;
int productArrayNumber = 0;
String nameFinder = "name:\"([\\w{1,15} ]*)";
String priceFinder = "price:(\\d{1,3})(.\\d{1,2})";
while ((inputLine = in.readLine()) != null){
Pattern namePattern = Pattern.compile(nameFinder);
Matcher nameMatcher = namePattern.matcher(inputLine);
Pattern pricePattern = Pattern.compile(priceFinder);
Matcher priceMatcher = pricePattern.matcher(inputLine);
while(nameMatcher.find()){
exists = false;
name = nameMatcher.group(1);
for(int i = 0; i < productList.size();i++)
{
Product productExists = productList.get(i);
if(productExists.getProductName().equals(name))
{
exists = true;
}
}
if(exists== false)
{
Product productNew =new Product(name,null);
productList.add(productNew);
}
}
while(priceMatcher.find() && productArrayNumber<productList.size()){
price = priceMatcher.group(1);
price = price + priceMatcher.group(2);
Product productEdit = (Product) productList.get(productArrayNumber);
productEdit.setProductPrice(price);
productList.set(productArrayNumber, productEdit);
productArrayNumber++;
}
}
Product cheapest = null;
if(productList.size() != 0)
{
cheapest = productList.get(0);
for (int a = 0; a < productList.size()-1; a++)
{
System.out.println(productList.get(a));
Double chpPrice = Double.parseDouble(cheapest.getProductPrice());
Double cmpPrice = 500.0;
if(productList.get(a).getProductPrice() != null)
{
cmpPrice = Double.parseDouble(productList.get(a).getProductPrice());
if(chpPrice > cmpPrice)
{
cheapest = productList.get(a);
}
}
}
in.close();
}
return cheapest;
}
這樣的作品,感謝 –
接受,對不起,我是新來這裏張貼問題。 –