2013-07-26 29 views
1

我試圖從Java中使用 與匹配正則表達式提取一行的兩句話我行是這樣的,瀏覽器火狐=正則表達式在修剪前兩個字符

我使用下面的代碼

currentLine = currentLine.trim(); 
System.out.println("Current Line: "+ currentLine); 
Pattern p = Pattern.compile("(.*?)=(.*)"); 
Matcher m = p1.matcher(currentLine); 
if(m.find(1) && m.find(2)){ 
System.out.println("Key: "+m.group(1)+" Value: "+m.group(2)); 
} 

我得到的輸出是 重點:OWSER值:火狐

BR在我的情況下,修去。這對我來說似乎很奇怪,直到我知道它爲什麼會這樣,因爲這與PERL完美搭配。有人能幫我嗎?

+0

什麼是'currentLine'的價值?在'System.out.println(「當前行:」+ currentLine);'中打印的那個。 – acdcjunior

+0

@AdrianWragg(。*?)是無關的,它只是意味着一個非貪婪的匹配,這將使正則表達式引擎停止在第一個符號處,而不是吞噬一切,然後回溯。在這種情況下,這不是必須的,但可以稍微更高效。 – sundar

回答

0

您可以使用String.indexOf找到=的位置,然後String.substring讓你的兩個值:

String currentLine = "BROWSER=Firefox"; 

int indexOfEq = currentLine.indexOf('='); 

String myKey = currentLine.substring(0, indexOfEq); 
String myVal = currentLine.substring(indexOfEq + 1); 

System.out.println(myKey + ":" + myVal); 
2

當你調用m.find(2)它去除前兩個字符。 From the JavaDocs(粗體是礦):

public boolean find(int start)

重置此匹配器,然後嘗試找到匹配的圖案,開始指定索引處的輸入序列的下一個子序列。

所以,只使用m.find()

String currentLine = "BROWSER=FireFox"; 
System.out.println("Current Line: "+ currentLine); 
Pattern p = Pattern.compile("(.*?)=(.*)"); 
Matcher m = p.matcher(currentLine); 
if (m.find()) { 
    System.out.println("Key: "+m.group(1)+" Value: "+m.group(2)); 
} 

輸出:

Current Line: BROWSER=FireFox 
Key: BROWSER Value: FireFox 

See online demo here

+0

完美,這是正確的診斷和解決方案。這種形式的發現的鏈接是這個(儘管它只是在網頁上的下一個):http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html #尋找%28int 29% – sundar

相關問題