2017-07-26 41 views
2

我不是regexp的專家,這就是爲什麼我要求您建議在key = value組中分割此字符串的有效方法。使用正則表達式分割鍵=值組中的字符串(Java)

輸入字符串:

x-x="11111" y-y="John-Doe 23" db {rty='Y453'} code {codeDate='2000-03-01T00:00:00'} 

什麼,我需要的是讓key = value對:

key=x-x, value="11111" 
key=y-y, value="John-Doe 23" 
key=rty, value='Y453' 
key=codeDate, value='2000-03-01T00:00:00' 

我的解決辦法是在這裏,但我擔心這不是最簡單的一種。

String str = "x-x=\"11111\" y-y=\"John-Doe 23\" db {rty='Y453'} code {codeDate='2000-03-01T00:00:00'}"; 
Matcher m = Pattern.compile("(\\w+-*\\w*)=((\"|')(\\w+(|-|:)*)+(\"|'))").matcher(str); 

while(m.find()) { 
    String key = m.group(1); 
    String value = m.group(2); 
    System.out.printf("key=%s, value=%s\n", key, value); 
} 

在此先感謝您的幫助。

+0

單引號和雙引號之間的值選擇值千萬鍵總是由字母/數字,'_'和'-'字符? –

+0

鍵具有固定名稱:'x-x','y-y','rty'和'codeDate'。但在價值可以是任何東西.. – ayscha

回答

3

您可以使用此正則表達式與3個捕獲組和反向引用:

([\w-]+)=((['"]).*?\3) 

RegEx Demo

RegEx Breakup: 
  • ([\w-]+):比賽和組#捕獲鍵名1
  • =:比賽=
  • (:啓動組#2
    • (['"]):匹配並捕獲在組#3
    • .*?報價:匹配0或多個任意字符(懶惰匹配)
    • \3:返回參照組# 3,以匹配相同類型的閉引號
  • ):捕獲組#結束2

您將在.group(1).group(2)中得到您的匹配。

+1

實際上沒有正則表達式中的三個捕獲組? –

+0

是的,有三個:) – anubhava

+0

謝謝你的回答。現在我意識到我的錯誤和解決方案的過度複雜性。 :)其實這個解決方案可以使用的替代方案([\ w-] +)=((['「])。*?(['」])) – ayscha

0

在組1

String ResultString = null; 
try { 
    Pattern regex = Pattern.compile("[\"'](.*?[^\\\\])[\"']", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE); 
    Matcher regexMatcher = regex.matcher(subjectString); 
    if (regexMatcher.find()) { 
     ResultString = regexMatcher.group(1); 
    } 
} catch (PatternSyntaxException ex) { 
    // Syntax error in the regular expression 
} 
相關問題