2016-03-27 49 views
3

我希望能夠找到第一次出現的平方米,然後在它前面的數字,可能是整數或十進制數字。 例如: 「一些文本」 38平方米「一些文本」, 「一些文本」 48.8平方米「一些文本」, 「一些文本」 48平方米「一些文本」,等等。找到正則表達式和Java第一次出現

我有什麼到目前爲止是:

\ d \ d \ d \ s *(\米\ u00B2)| \ d \ d \ s *(\米\ u00B2)

這一權利現在發現所有的事件,雖然我猜它可以用findFirst()修復。任何想法如何改進正則表達式部分?

+1

檢查:HTTP:// stackoverflow.com/questions/18838906/java-regex-first-match-only –

+2

使用'Matcher.find'。 –

+1

請顯示代碼。使用'if'而不是'while'和'Matcher#find()'。模式可以縮短爲'\ d +(?:,\ d +)?\ s * m \ u00B2' –

回答

2

要獲得第一場比賽,你只需要使用Matcher#find()if塊中:

String rx = "\\d+(?:,\\d+)?\\s*m\\u00B2"; 
Pattern p = Pattern.compile(rx); 
Matcher matcher = p.matcher("E.g. : 4668,68 m² some text, some text 48 m² etc"); 
if (matcher.find()){ 
    System.out.println(matcher.group()); 
} 

使用可選的非捕獲見IDEONE demo

請注意,您可以擺脫交替組組(?:..)?

模式擊穿:

  • \d+ - 1+數字
  • (?:,\d+)? - 逗號的序列0+隨後與1+數字
  • \s* - 0+空格符號
  • m\u00B2 - 平方米。
+1

建議:在數字附近添加捕獲組,因此可以使用'group(1)'提取並使用'DecimalFormat' 。 – Andreas

+0

當然,可以在數字周圍設置捕獲組,只是OP原始模式沒有該組。 –

0

這是我與你想出了幫助:)(工作正在進行中,稍後應該返回BigDecimal的值),現在它似乎工作:

public static String findArea(String description) { 

     String tempString = ""; 
     Pattern p = Pattern.compile("\\d+(?:,\\d+)?\\s*m\\u00B2"); 

     Matcher m = p.matcher(description); 

     if(m.find()) { 
      tempString = m.group(); 
     } 
//remove the m and /u00B2 to parse it to BigDecimal later 
     tempString = tempString.replaceAll("[^0-9|,]",""); 
     System.out.println(tempString); 
     return tempString; 
    } 
相關問題