How to use double brackets in a regular expression?

后端 未结 2 408
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 23:16

    '[[' doesn't have any special meaning. [xyz] is a character class and will match a single x, y or z. The carat ^ takes all characters not in the brackets.

    Removing ^ for simplicity, you can see that the first open bracket is being matched with the first close bracket and the second closed bracket is being used as part of the character class. The final close bracket is treated as another character to be matched.

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

    This appears to have the same result as your original in some cases

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

    But this is only because your regular expression is not looking for an exact match.

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

提交回复
热议问题