2017-09-12 34 views
1

欲下面串 (1)數 (2)字符串分割在三個部分,直到第一次出現「」 (3)的其餘字符串分割字符串使用Pattern和Matcher直至第一次出現「」

Like if the string is "12345 - electricity, flat no 1106 , Palash H , Pune" 
Three parts should be 
(1) 12345 
(2) electricity 
(3) flat no 1106 , Palash H , Pune 

我能夠使用下面的代碼拆分爲12345和字符串的其餘部分。但不能根據需要打破第二和第三部分

Map<String, String> strParts= new HashMap<String, String>(); 
String text = "12345 - electricity, flat no 1106 , Palash 2E , Pune"; 
Pattern pttrnCrs = Pattern.compile("(.*)\\s\\W\\s(.*)"); 
Matcher matcher = pttrnCrs.matcher(text); 
if (matcher.matches()) { 
    strParts.put("NUM", matcher.group(1)); 
    StrParts.put("REST", matcher.group(2)); 
} 

任何人都可以幫忙嗎?

回答

1

你需要使用正則表達式與3個捕獲組:

^(\d+)\W*([^,]+)\h*,\h*(.*)$ 

RegEx Demo

在Java中使用:

final String regex = "(\\d+)\\W*([^,]+)\\h*,\\h*(.*)"; 

無需在Java中使用錨如果您正在使用Matcher#matches()隱式錨定正則表達式的方法。

正則表達式破碎:

^   # start 
(\d+)  # match and group 1+ digits in group #1 
\W*  # match 0 or more non-word characters 
([^,]+) # Match and group 1+ character that are not comma in group #2 
\h*,\h* # Match comma surrounded by optional whitespaces 
(.*)  # match and group remaining characters in string in group #3 
$   # end 
+1

是anubhava它的工作。你能否給我建議任何網站/學習材料,以學習Java中的reg。我對這個領域完全陌生 –

+0

你可以關注這個很好的網站來學習正則表達式:http://regular-expressions.info – anubhava

+0

感謝Anubhava 需要一個更多的幫助,這段代碼在我的本地工作正常,但是當我運行它在Jenkins服務器上我得到下面Errorjava.util.regex.PatternSyntaxException:索引16附近的非法/不受支持的轉義序列 (\ d +)\ W *([^,] +)\ h *,\ h *(。* ) ^ \t at java.util.regex.Pattern.error(Pattern.java:1924) 是否需要對Java版本進行任何操作 –

相關問題