2016-10-18 62 views
-1

我試圖在java中使用regex從字符串中提取一些信息。對於演示,我有以下的(貌似愚蠢的代碼):正則表達式匹配一個字符串,但失敗

Pattern featureIndexValuePattern = Pattern.compile("([\\w_ \\-\\.\\=]+)\\s+(\\d+)"); 


String str = "member_currentCompany9042547 0"; 

String str1 = "member_currentCompany9042547 0"; 

Matcher match = featureIndexValuePattern.matcher(str); 

if (match.find()) { 
    System.out.println("FOUND!"); 
    System.out.println(match.group(0)); 
    System.out.println(match.group(1)); 
    System.out.println(match.group(2)); 
} 

match = featureIndexValuePattern.matcher(str1); 

if (match.find()) { 
    System.out.println("FOUND!"); 
    System.out.println(match.group(0)); 
    System.out.println(match.group(1)); 
    System.out.println(match.group(2)); 
} 

我得到的輸出是

FOUND! 
9042547 0 
9042547 
0 
FOUND! 
member_currentCompany9042547 0 
member_currentCompany9042547 
0 

其實兩個輸入字符串是完全一樣的,除了第一種是從複製粘貼一個文件和後者是硬編碼的。我無法找到爲什麼產量不同。我懷疑這是字符編碼。有人能幫我理解這裏發生了什麼嗎?

感謝, 尼基爾

+3

嘗試打印'str.equals(str1)'。例如,可能存在差異。非打印空格,非打斷空格等。如果不相同,則打印'Arrays.toString(str.toCharArray())',對於'str1'則相同,以便更容易地看到差異。 –

+1

我使用你的代碼得到[相同的結果](https://ideone.com/dRYdvg)。 –

+0

'str.equals(str1)'返回'false'。 –

回答

0

Andy Turner的在評論中建議,進行

Arrays.toString(str.toCharArray()) 

我能看見非打印Unicode字符(9點前)時:

str: [m, e, m, b, e, r, _, c, u, r, r, e, n, t, C, o, m, p, a, n, y, , 9, 0, 4, 2, 5, 4, 7, , 0] 
str1: [m, e, m, b, e, r, _, c, u, r, r, e, n, t, C, o, m, p, a, n, y, 9, 0, 4, 2, 5, 4, 7, , 0] 

添加\\p{C}以解決問題。

Nikhil