2012-09-05 59 views
8

雙正方括號在正則表達式中意味着什麼?我感到困惑下面的例子:如何在正則表達式中使用雙括號?

/[[^abc]]/ 

/[^abc]/ 

使用Rubular我測試,但我沒有看到一個雙括號,括號單任何區別。

+0

我創建[展開 - 括號](https://www.npmjs.com/package/展開括號),如果你有興趣看到與posix字符類匹配的javascript實現 – jonschlinkert

回答

8

Posix character classes使用[:alpha:]符號,其中使用正則表達式中,如:

/[[:alpha:][:digit:]]/ 

你需要向下滾動的方式去在上面的鏈接POSIX的信息。從文檔:

POSIX括號表達式也類似於字符類。它們爲上述提供了一種便攜式替代方案,而且還包含非ASCII字符。例如,/ \ d /只匹配ASCII十進制數字(0-9);而/ [[:digit:]] /匹配Unicode Nd類別中的任何字符。

/[[:alnum:]]/ - Alphabetic and numeric character 
/[[:alpha:]]/ - Alphabetic character 
/[[:blank:]]/ - Space or tab 
/[[:cntrl:]]/ - Control character 
/[[:digit:]]/ - Digit 
/[[:graph:]]/ - Non-blank character (excludes spaces, control characters, and similar) 
/[[:lower:]]/ - Lowercase alphabetical character 
/[[:print:]]/ - Like [:graph:], but includes the space character 
/[[:punct:]]/ - Punctuation character 
/[[:space:]]/ - Whitespace character ([:blank:], newline, 
carriage return, etc.) 
/[[:upper:]]/ - Uppercase alphabetical 
/[[:xdigit:]]/ - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F) 

紅寶石還支持以下非POSIX字符類:

/[[:word:]]/ - A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation 
/[[:ascii:]]/ - A character in the ASCII character set 
# U+06F2 is "EXTENDED ARABIC-INDIC DIGIT TWO" 

/[[:digit:]]/.match("\u06F2") #=> #<MatchData "\u{06F2}"> 
/[[:upper:]][[:lower:]]/.match("Hello") #=> #<MatchData "He"> 
/[[:xdigit:]][[:xdigit:]]/.match("A6") #=> #<MatchData "A6"> 
+0

此答案已添加到[字符類別]下的[Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496)。 – aliteralmind

4

'[['沒有任何特別的含義。 [xyz]是一個字符類,將匹配一個單獨的x,yz。克拉^採取所有不在括號中的字符。

爲簡單起見,刪除^可以看到第一個開放式支架與第一個緊密支架相匹配,而第二個封閉支架正用作角色類的一部分。最後的右括號被視爲另一個要匹配的字符。

irb(main):032:0> /[[abc]]/ =~ "[a]" 
=> 1 
irb(main):033:0> /[[abc]]/ =~ "a]" 
=> 0 

這似乎有相同的結果,你原來在某些情況下

irb(main):034:0> /[abc]/ =~ "a]" 
=> 0 
irb(main):034:0> /[abc]/ =~ "a" 
=> 0 

但是,這僅僅是因爲你的正則表達式是不是找一個精確匹配。

irb(main):036:0> /^[abc]$/ =~ "a]" 
=> nil 
+1

請注意,這不是所有的正則表達式風格。例如,Java將它視爲一個只包含另一個字符類的字符類,因此'[[^ abc]]'和'[^ abc]'實際上是相同的。 –

+0

FWIW - Python與上面的答案具有相同的行爲,不確定其他語言或者它應該做什麼,儘管我更喜歡@AlanMoore提到的行爲。 – dfb

相關問題