2017-08-09 59 views
2

我有一個string像波紋管:常規價格表達 - Android電子

dfdfm;lg 2500$ jshfsnefsfz5405€mnvkjdf64rfmkd554668¢ odsfrknegj 885486¥ dsflkef 588525dollar 

我得到波紋管的值與此[\\d,]+\\s*\\$|[\\d,]+\\s*€|[\\d,]+\\s*¥|[\\d,]+\\s*¢|[\\d,]+\\s*dollar

2500 $ 5405€ 554668¢ 885486¥ 588525dollar

問題:但我不需要這些$ € ¢ ¥ dollar。我怎樣才能刪除這些頂級正則表達式?

這裏是我的方法:

private String getPrice(String caption) { 
    String pricePattern = "[\\d,]+\\s*\\$|[\\d,]+\\s*€|[\\d,]+\\s*¥|[\\d,]+\\s*¢|[\\d,]+\\s*dollar|[\\d,]+\\s*Euro"; 
    List<String> lstPrice = new ArrayList<>(); 
    Pattern rPrice = Pattern.compile(pricePattern); 
    Matcher mPrice = rPrice.matcher(caption); 
    while (mPrice.find()) { 
     lstPrice.add(mPrice.group()); 
    } 
    if (lstPrice.size() > 0) { 
     return lstPrice.get(0); 
    } 
    return ""; 
} 
+1

使用組'([\\ d,] +) '和你的正則表達式也可以優化 –

+0

也許我有這樣一個字符串:dsfsdfd58ssdf8745 $。然後讓我58和8745。我只需要價格。 –

+0

我只需要價格。 –

回答

1

如果需要返回所有的價格,請確保您的getPrice方法返回List<String>和調整正則表達式匹配的價格,但只捕捉數字:

private List<String> getPrice(String caption) { 
    String pricePattern = "(?i)(\\d[\\d,]*)\\s*(?:[$€¥¢]|dollar|Euro)"; 
    List<String> lstPrice = new ArrayList<>(); 
    Pattern rPrice = Pattern.compile(pricePattern); 
    Matcher mPrice = rPrice.matcher(caption); 
    while (mPrice.find()) { 
     lstPrice.add(mPrice.group(1)); 
    } 
    return lstPrice; 
} 

請參閱Java demo online

String s = "dfdfm;lg 2500$ jshfsnefsfz5405€mnvkjdf64rfmkd554668¢ odsfrknegj 885486¥ dsflkef 588525dollar"; 
System.out.println(getPrice(s)); 

返回

[2500, 5405, 554668, 885486, 588525] 

圖案的詳細資料

  • (?i) - 不區分大小寫的改性劑(嵌入標誌選項)
  • (\\d[\\d,]*) - 第1組捕獲一個數字,然後0 +數字或,
  • \\s* - 0+空格
  • (?:[$€¥¢]|dollar|Euro) - 要麼$¥¢,或dollareuro(不區分大小寫搜索經由(?i)啓用)
+1

@ WiktorStribiżew。你的回答是真實的。非常感謝 。 –

+0

接受這個問題。 –

1

你可以嘗試用的replaceAll

替換的 模式與給定替換字符串匹配的輸入序列的每個子。

String pricePattern="2500$ 5405€ 554668¢ 885486¥ 588525dollar"; 
pricePattern= pricePattern.replaceAll("[^\\d+]", " "); //2500 5405 554668 885486 588525 

檢查Java Demo

+0

你應該指定你正在談論後處理。我相信想要修改他的正則表達式,所以它同時做到了。 – Nathan

+1

@ IntelliJ Amiya。你的回答是真實的。非常感謝 。 –

+0

此方法還會保留不屬於價格的其他數字(如年,小時等)。當只有價格時,此方法適用於某些邊緣情況,輸入字符串中不包含其他數字。 –