0

我有一个字符串是:

<p>1+: €0,09756<br>3.001+: €0,09338<br>
30.001+: €0,09338<br>150.001+: €0,09338<br>
750.001+: €0,09338<br>
</p>

现在我想做的是我想调用article.addPrice(new Integer(quantity), new Float(price));这些由<br>. 意思是结果是:

article.addPrice(new Integer(1), new Float(0.09756));
article.addPrice(new Integer(3001), new Float(0.09338));
article.addPrice(new Integer(30001), new Float(0.09338));
article.addPrice(new Integer(150001), new Float(0.09338));
article.addPrice(new Integer(750001), new Float(0.09338));

整数被去除所有特殊字符,浮点数也是如此。货币符号将被忽略。如果下一行的价格与之前的价格相同,article.addPrice则不会执行。

这样做最有效的方法是什么?

4

3 回答 3

2

使用followig正则表达式怎么样?

(\d+(,\d+)?)\+: €(\d+(,\d+)?(\.\d+)?)

编辑(由 abhusava 提供):

String str = "<p>1+: €0.09756<br>3,001+: €0.09338<br>\n" + 
   "30,001+: €0.09338<br>150,001+: €0.09338<br>750,001+: €0.09338<br></p>";

Pattern pt = Pattern.compile("(\\d+(,\\d+)?)\\+: €(\\d+(,\\d+)?(\\.\\d+)?)");
Matcher m = pt.matcher(str);    
Float lastPrice = null;

while(m.find()) {
  Integer quantity = new Integer(m.group(1).replace(",",""));
  Float price = new Float(m.group(3).replace(",","").replace(".",","));

  // Only add price if different from last
  if (! price.equals(lastPrice))
    article.addPrice(quantity, price);
  lastPrice = price;
}
于 2012-05-06T17:53:59.717 回答
2

对于初学者,用 . 分割字符串s.split("<br>")。这会根据要求为您提供一个字符串数组。你还需要消除启动<p>。然后,您可以使用 . 拆分数组中的每个条目split("\\+: €")。这为您留下了一个可解析为数字的字符串的二元素数组,除了逗号,您需要将其替换为点:s.replace(',', '.')。最后,使用Integer.parseIntFloat.parseFloat

于 2012-05-06T17:54:21.640 回答
0

考虑这段代码:

String str = "<p>1+: €0,09756<br>3.001+: €0,09338<br>\n" + 
   "30.001+: €0,09338<br>150.001+: €0,09338<br>750.001+: €0,09338<br></p>";
Pattern pt = Pattern.compile("([^\\+]+)\\D+([\\d,]+)");
Matcher m = pt.matcher(str);
while(m.find()) {
    int quantity = Integer.parseInt(m.group(1).replaceAll("\\D+", ""));
    float price = Float.parseFloat(m.group(2).replace(',', '.'));
    System.out.printf("article.addPrice(new Integer(%d), new Float(%f));%n",
                       quantity, price);
}

输出:

article.addPrice(new Integer(1), new Float(0.09756));
article.addPrice(new Integer(3001), new Float(0.09338));
article.addPrice(new Integer(30001), new Float(0.09338));
article.addPrice(new Integer(150001), new Float(0.09338));
article.addPrice(new Integer(750001), new Float(0.09338));
于 2012-05-06T18:27:49.510 回答