2013-03-25 69 views
2

我使用的正則表達式在RegexBuddy中工作,但在Java中不起作用。正則表達式在Java中沒有像預期的那樣工作

這是我的正則表達式:(?<=(files)\\s)(.*)

這是我在測試它的字符串:"–files /root1/file1.dat;/root/file2.txt"

在使用RegexBuddy它的返回:"/root1/file1.dat;/root/file2.txt"但在Java它返回只是字面字files

爲什麼不能正常工作?

+2

當你說「它回來了......」你究竟是什麼意思?你的原始正則表達式應該有'matcher.group()'和'matcher.group(2)'包含'/ root1/.....',但是'matcher.group(1)'將包含字符串'files',因爲捕獲括號內的括號。 – 2013-03-25 23:18:55

+0

@IanRoberts我使用組(1)犯了錯誤。我得到解釋後,我已經修復了代碼,現在應該是。 – user2205591 2013-03-25 23:43:51

回答

3

試試這個正則表達式:

(?<=files\\s)(.*) 

編輯附加解釋

我猜你服用group(1)

您正則表達式:(?<=(files)\\s)(.*)有三個比賽組:

group 0:/root1/file1.dat;/root/file2.txt 
group 1:files 
group 2:/root1/file1.dat;/root/file2.txt 

礦:(?<=files\\s)(.*)有兩個:

group 0:/root1/file1.dat;/root/file2.txt 
group 1:/root1/file1.dat;/root/file2.txt 

在向後看組其實是沒有必要的,而且你(.*)成爲group(2)如果你想獲得'/root1.....$」,你不必須分組,

(?<=files\\s).* 

會做這項工作。

無論如何,如果你要堅持你的正則表達式,採取group(2)

我希望這是明確的解釋。

+0

謝謝。在這種情況下,是否有關於括號的規則很好知道? – user2205591 2013-03-25 23:08:23

+0

好的我正在編輯答案 – Kent 2013-03-25 23:11:23

+0

@HugoDozois請參閱編輯。 – Kent 2013-03-25 23:20:54

0

奇怪的是,我運行這個,我看到沒有區別,如果我把括號放在文件或沒有。外觀內的支架沒有區別。

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class regex 
{ 
    public static void main(String[] args) 
    { 

     String s = "-files /root1/file1.dat;/root/file2.txt"; 
     Pattern p = Pattern.compile("(?<=-(files)\\s)(.*)"); 
     Matcher m = p.matcher(s); 
     System.out.println(m.find()); 
     System.out.println(m.group()); 
    } 
} 

請注意,如果你正在試圖解析命令行參數,這樣便很可能是因爲你會遇到的問題(可能)與此重疊的其他參數是一個壞主意。那麼像「-docs freds-files -files blah.txt」這樣的情況呢?

+0

問題是我使用組(1)。我知道正則表達式並不完美,但我正在做的項目沒有關係。我只需要將代碼放入該正則表達式中,以便在最後一個空格之後停止返回 – user2205591 2013-03-25 23:49:17

相關問題