How do I match a square bracket literal using RegEx?

前端 未结 6 1938
灰色年华
灰色年华 2021-02-07 00:27

What\'s the regex to match a square bracket? I\'m using \\\\] in a pattern in eregi_replace, but it doesn\'t seem to be able to find a ]..

6条回答
  •  长发绾君心
    2021-02-07 01:11

    There are two ways of doing this:

    / [\]] /x;
    
    /  \]  /x;
    

    While you may consider the latter as the better option, and indeed I would consider using it in simpler regexps. I would consider the former, the better option for larger regexps. Consider the following:

    / (\w*) (  [\d\]] ) /x;
    
    / (\w*) ( \d | \] ) /x;
    

    In this example, the former is my preferred solution. It does a better job of combining the separate entities, which may each match at the given location. It may also have some speed benefits, depending on implementation.

    Note: This is in Perl syntax, partly to ensure proper highlighting.
    In PHP you may need to double up on the back-slashes. "[\\]]" and "\\]"

提交回复
热议问题