2015-09-10 19 views
0

我有這樣一個文件中的一些文字:正則表達式檢查與打頭[和結束]

[ABM-100] 
0x00,Hours  
0x01,Minutes 
0x06,T2  

[CO2SMO] 
1 ,Instrument 
2 ,Time    
3 ,AAI    

我想要得到的文本[和],如ABM-100和CO2SMO。 我嘗試使用正則表達式匹配,但結果是

[ABM-100] 
0x00,Hours  
0x01,Minutes 
0x06,T2  

[CO2SMO] 

我已經試過以下

line.matches("^\\[.*.\\]$") 
+0

你的問題很混亂。 「匹配」只返回true或false,而不是文本。另外,如果'lines'代表許多行的文本構建,那麼點'.'將無法接受它們,因爲它不能匹配'\ n'或'\ r'。 – Pshemo

+0

這樣的事情如何:\ [([^ \]] *)\]。 https://regex101.com/r/vA9wV2/1 – lintmouse

回答

1

你不顯示完整的代碼,但是代碼line.matches("^\\[.*.\\]$")意味着你單獨檢查每一行。

如果你想捕獲的是一塊匹配的文本,你應該使用一個捕獲組。

由於您使用的是matches(),因此不需要錨點(^$),並且額外的.是多餘的。

這說明如何做到這一點:

String[] lines = { "[ABM-100]", 
        "0x00,Hours ", 
        "0x01,Minutes ", 
        "0x06,T2  ", 
        "", 
        "[CO2SMO]", 
        "1 ,Instrument", 
        "2 ,Time    ", 
        "3 ,AAI " }; 
Pattern p = Pattern.compile("\\[(.*)\\]"); 
for (String line : lines) { 
    Matcher m = p.matcher(line); 
    if (m.matches()) 
     System.out.println(m.group(1)); 
} 

輸出

ABM-100 
CO2SMO 

如果line不同時代表一行,而是整個文本,你需要使用find(),並通過指定使^$錨點符合行首和行尾flag:

String text = "[ABM-100]\n" + 
       "0x00,Hours \n" + 
       "0x01,Minutes \n" + 
       "0x06,T2  \n" + 
       "\n" + 
       "[CO2SMO]\n" + 
       "1 ,Instrument\n" + 
       "2 ,Time    \n" + 
       "3 ,AAI \n"; 
Pattern p = Pattern.compile("^\\[(.*)\\]$", Pattern.MULTILINE); 
Matcher m = p.matcher(text); 
while (m.find()) 
    System.out.println(m.group(1)); 

輸出是一樣的。

0

你並不需要爲這個正則表達式,因爲你可以做line.startsWith("[") && line.endsWith("]");,它會要快得多。

+0

我想你的意思是'line.endsWith(「]);' – ControlAltDel

0

.*是貪婪的,這意味着您的正則表達式將嘗試匹配它找到的第一個[]之間的最大可能範圍。您可以嘗試使.*不願意添加?,如.*?。您也可以用[^\\]]替換.以避免匹配]

另外matches檢查整個字符串是否匹配正則表達式,它不返回匹配。我懷疑你可能要使用

Pattern p = Pattern.compile(yourRegex); 
Matcher m = p.matcher(text); 
while(m.find()){ 
    String match = m.group(); 
    //do what you want with match like: 
    System.out.println(match); 
}