2011-10-06 43 views
0

你能解釋下面的正則表達式的語義嗎?特別是,什麼?:()是什麼意思?關於Javascript的問題正則表達式語法

/(?:^|:|,)(?:\s*\[)+/g 

謝謝。

+0

https://developer.mozilla.org/zh/JavaScript/Guide/Regular_Expressions –

回答

1

?:^|手段 - 匹配線路或比賽的開始,但沒有捕捉到組或背部存儲裁判

?:意味着 - 不捕獲組或背部存儲裁判

1

()告訴解析器捕獲匹配以便引用它。

?:()裏面告訴解析器沒有捕捉到比賽

這是整個解釋:

Match the regular expression below «(?:^|:|,)» 
    Match either the regular expression below (attempting the next alternative only if this one fails) «^» 
     Assert position at the beginning of the string «^» 
    Or match regular expression number 2 below (attempting the next alternative only if this one fails) «:» 
     Match the character 「:」 literally «:» 
    Or match regular expression number 3 below (the entire group fails if this one fails to match) «,» 
     Match the character 「,」 literally «,» 
Match the regular expression below «(?:\s*\[)+» 
    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    Match a single character that is a 「whitespace character」 (spaces, tabs, and line breaks) «\s*» 
     Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
    Match the character 「[」 literally «\[» 

閱讀Regular Expression Advanced Syntax Reference關於這一點,其他的正則表達式語法的解釋說明。

+0

您可能想要解釋*爲什麼*您希望使用非捕獲組(以限制交替操作符的範圍,使其具有一個量詞可以應用於的單位等) –

+0

@TimPietzcker我回答基於OP的懷疑。可以有任何理由爲什麼你想要一個非捕獲組,但最常見的是因爲你不希望它是一個。在這種情況下,顯而易見的是,括號用於第一組上的交替操作符,並且在第二組上具有量化符。它可能是一個捕獲組,對此沒有嚴格的規定。 – Shef

1

?:表示不匹配的組。通常()會保存替換參考。

因此, 「ABC」 .replace(/.(.)./, 「X $ 1X」)將返回 「XBX」

然後加入:對待它們,就像組,但不保存,以備日後。在HTML正則表達式

典型用法是像 標籤 < *(?:HREF | SRC)=「['」]

這看起來對HREF或SRC屬性,然後保存價值。

1

使用括號()可以將一些東西組合在一起,例如,對於(?:\s*\[)+量詞+(一個或多個)屬於整個組\s*\[,這意味着它將在每個方括號之前匹配多個[以及可選空白。

這些組是默認的捕獲組,這意味着匹配的部分被放入一個變量,並可以使用反向引用,或只是作爲結果。

該默認行爲可以通過將?:放在前括號後面進行更改,因此(?:\s*\[)+是非捕獲組,即匹配的部分未存儲在某處。