如何在正则表达式中使用双括号? [英] How to use double brackets in a regular expression?
问题描述
双方括号在正则表达式中是什么意思?我对以下示例感到困惑:
What do double square brackets mean in a regex? I am confused about the following examples:
/[[^abc]]/
/[^abc]/
我正在使用 Rubular 进行测试,但我没有看到双括号和单括号之间的任何区别.
I was testing using Rubular, but I didn't see any difference between the one with double brackets and single brackets.
推荐答案
Posix character classes use a [:alpha:]
notation, which are used inside a regular expression like:
a> 使用 [:alpha:]
表示法,在正则表达式中使用,例如:
/[[:alpha:][:digit:]]/
You'll need to scroll down a ways to get to the Posix information in the link above. From the docs:
您需要向下滚动以获取以上链接中的 Posix 信息.来自文档:
POSIX bracket expressions are also similar to character classes. They provide a portable alternative to the above, with the added benefit that they encompass non-ASCII characters. For instance, /\d/ matches only the ASCII decimal digits (0-9); whereas /[[:digit:]]/ matches any character in the Unicode Nd category.
POSIX 括号表达式也类似于字符类.它们为上述提供了一种可移植的替代方案,并具有包含非 ASCII 字符的额外好处.例如,/\d/只匹配 ASCII 十进制数字 (0-9);而/[[:digit:]]/匹配 Unicode Nd 类别中的任何字符.
<块引用>
Ruby 还支持以下非 POSIX 字符类:
Ruby also supports the following non-POSIX character classes:
/[[: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">
这篇关于如何在正则表达式中使用双括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!