How to use double brackets in a regular expression?

后端 未结 2 407
Happy的楠姐
Happy的楠姐 2020-12-03 22:31

What do double square brackets mean in a regex? I am confused about the following examples:

/[[^abc]]/

/[^abc]/
         


        
2条回答
  •  清歌不尽
    2020-12-03 22:57

    Posix character classes use a [:alpha:] notation, which are used inside a regular expression like:

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

    You'll need to scroll down a ways to get to the Posix information in the link above. From the docs:

    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.

    /[[: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)
    

    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")    #=> #
    /[[:upper:]][[:lower:]]/.match("Hello") #=> #
    /[[:xdigit:]][[:xdigit:]]/.match("A6")  #=> #
    

提交回复
热议问题