2013-06-25 23 views
0

我想從字符串之間使用正則表達式的撇號中獲取子字符串。 字符串的格式:Duplicate entry '[email protected]' for key 'email'。 正在使用的正則表達式:'([^']*)如何獲取撇號之間的數據Android

代碼:

Pattern pattern = Pattern.compile("'([^']*)"); 
Matcher matcher = pattern.matcher(duplicated); 
Log.d(TAG, matcher.group())); 

我不也肯定matcher.group(),它返回一個字符串,匹配整個正則表達式。在我的情況下,它應該返回兩個子字符串。

有人可以糾正這個正則表達式並給我一個解釋嗎? 在此先感謝

回答

2

更好地使用.split()而不是模式匹配。它只是硬編碼。做如下:

String[] strSplitted = <Your String>.split("`"); 

然後,strSplitted數組包含`之間分裂的字符串。

+0

是的,一開始我想做到像但它返回「重複條目」,「[email protected]」,「關鍵」,「電子郵件」。雖然我不知道方法「split()」的效率,但是我認爲只返回「[email protected]」和「email」的正則表達式會更加有效,和「matcher()」:)。所以說說split()更好,好嗎? – Husky

+0

'Matcher()'由於遇到問題而最終失敗。儘量避免這種情況。 'split()'比'Regex'具有更少的時間複雜度。我的建議是更好使用'split()' –

+0

好的,謝謝:) – Husky

1

我會用這個正則表達式。它幾乎和你的完全一樣,但是我包含了最後的單引號。這是爲了防止在下一場比賽中使用結束單引號。

matcher.group(1) 

這裏是一個Java示例:

Pattern regex = Pattern.compile("'([^']*)'", Pattern.MULTILINE); 
Matcher matcher = regex.matcher(duplicated); 
while (matcher.find()) { 
    Log.d(TAG, matcher.group(1))); 
} 
+0

我已經試過這個,但「輸出」是:java.lang.IllegalStateException:迄今沒有成功的匹配。 – Husky

+0

@Husky - 根據這個http://stackoverflow.com/questions/9893875/debugging-pattern-regex-failure-in-in-java-android你需要先打電話找。也許你可以嘗試我的解決方案中的示例代碼。 –

+0

是的,我剛剛閱讀了有關find()的文檔 - >「在輸入中返回模式的下一次出現」 – Husky

1

這是我測試的解決方案

'([^']*)' 

而且裏面的單引號使用類似於此行獲得的內容。你必須調用find

Pattern pattern = Pattern.compile("'([^']*)'"); 
String duplicated = "Duplicate entry '[email protected]' for key 'email'"; 
Matcher matcher = pattern.matcher(duplicated); 

String a = ""; 
while (matcher.find()) { 
    a += matcher.group(1) + "\n"; 
} 

結果:

[email protected] 
email 
1

我創造我的解決方案類似以下。

int second_index = 0; 
String str = "Duplicate entry '[email protected]' for key 'email'"; 
while (true) { 
    if (second_index == 0) 
     first_index = str.indexOf("'", second_index); 
    else 
     first_index = str.indexOf("'", second_index + 1); 

    if (first_index == -1) 
     break; 

    second_index = str.indexOf("'", first_index + 1); 

    if (second_index == -1) 
     break; 

    String temp = str.substring(first_index + 1, second_index); 

    Log.d("TAG",temp); 
} 

輸出

06-25 17:25:17.689:[email protected]
06-25 17:25:17.689:電子郵件

+0

我也在考慮這個問題,但我試圖以一切都很簡單的方式編寫這個應用程序儘可能(用最少數量的條件等)試圖避免這種解決方案:)。 (我並不是說你的解決方案很複雜或是某些問題,但我只是不想簡單地用這麼多「if」來解決這麼簡單的任務)。無論如何,大拇指! :) – Husky

+0

@赫斯基,親愛的我沒有問題。我得到這個問題,直到除非我找到解決方案,我自己意味着我的自定義代碼,它能夠做我想要的定製,我無法入睡。順便提一下,你已經檢查過這個。 :) –

相關問題