2011-11-19 64 views
0

我想了解下面的內容。瞭解這個正則表達式

^([^=]+)(?:(?:\\=)(.+))?$ 

任何想法?

這是在這裏使用。顯然它是命令行解析器,但我試圖理解語法,所以我實際上可以運行該程序。這是從commandline-jmxclient,他們沒有設置JMX屬性的文件,但在他們的源代碼中,有這樣的選項,所以我只想了解我可以如何調用該方法。

Matcher m = Client.CMD_LINE_ARGS_PATTERN.matcher(command); 
    if ((m == null) || (!m.matches())) { 
    throw new ParseException("Failed parse of " + command, 0); 
    } 

    this.cmd = m.group(1); 
    if ((m.group(2) != null) && (m.group(2).length() > 0)) 
    this.args = m.group(2).split(","); 
    else 
    this.args = null; 
+0

兩個最佳答案都是正確的(Dmitry's和FailedDev's)。應該指出的是,這個正則表達式可以簡化爲 –

回答

4

好解釋讀了會是這樣:

" 
^   # Assert position at the beginning of the string 
(   # Match the regular expression below and capture its match into backreference number 1 
    [^=]  # Match any character that is NOT a 「=」 
     +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 
(?:   # Match the regular expression below 
    (?:   # Match the regular expression below 
     =   # Match the character 「=」 literally 
    ) 
    (   # Match the regular expression below and capture its match into backreference number 2 
     .   # Match any single character that is not a line break character 
     +   # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
    ) 
)?   # Between zero and one times, as many times as possible, giving back as needed (greedy) 
$   # Assert position at the end of the string (or before the line break at the end of the string, if any) 
" 

將捕捉一切=以引用1和之前的一切後它backrefrence 2.

例如

33333098320498 
adhajdh =3232-40923-04924-0924 

對於第一個字符串,一切都被捕獲到$ 1。

對於第二個:

adhajdh <---------- captured to $1 
3232-40923-04924-0924 <----- captured to $2 
+0

我真的不認爲那些帶註釋的正則表達式樹是值得的;太多的細節,太多的重複,不夠大的圖片。 –

+0

@AlanMoore他們幫助我學習了很多,雖然:) – FailedDev

5

它說:「‘=’任選隨後用‘=’後面跟着任何數目的字符不屬於任何數目的字符」

,但你真的應該regular expressions

+0

+ 1的答案,我真的在非常罕見的情況下遇到了正則表達式。從來不需要閱讀它。 – DarthVader

1

首先,讓我們確保我們都在談論同樣的正則表達式。它可能創造這樣的事情:

public static final Pattern CMD_LINE_ARGS_PATTERN = 
    Pattern.compile("^([^=]+)(?:(?:\\=)(.+))?$"); 

中的雙反斜線(\\=)獲取Java編譯器轉換爲一個反斜槓,所以Pattern.compile()認爲這是\=,轉義等號。順便說一下,這不需要逃避; ^([^=]+)(?:=(.+))?$也可以工作。

總之,該代碼在這些形式之一尋找一個命令:

command 
command=arg 
command=foo,bar 
command=abc,123,xyz 

...等等。第一部分正則表達式 - ([^=]+) - 捕獲「命令」,即在第一個等於(如果有)之前的所有內容,如果不是,則爲整個字符串。將第二部分作爲可選項,並將其與一個由量化器控制的未捕獲組相關聯。如果有等號(?:\\=)會消耗它,然後(.+)將捕獲字符串的其餘部分。

如果匹配成功,該命令將被捕獲到組#1中,但我們還不知道是否有參數列表。如果沒有等號,第二個捕獲組將不會參加比賽,m.group(2)將返回null。否則,我們將它分成逗號分開各個參數。

但是,該代碼只會把你帶到目前爲止。它也會接受這些輸入,但是您必須測試它們以查看它們是否有效:

command= foo , bar # surrounding spaces okay/will be trimmed? 
command=foo bar  # internal spaces okay? 
command=foo,  # one-item args list, no problem 
command=,   # zero-item args list, could be trouble