0

I have a string which is:

<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>

Now what I would like to do is I would like to call article.addPrice(new Integer(quantity), new Float(price)); for each of these lines which are separated by the <br>. Meaning the result is:

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));

The integer is stripped of all special characters, the float too. The currency symbol will be ignored. If the Price of the next line is the same as the one before the article.addPrice will not be performed.

What is the most efficient way of doing this?

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("\\+: €")。これにより、数値に解析可能な文字列の2要素配列が残ります。ただし、コンマを除き、ドットで置き換える必要があります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 に答える