How do I match a square bracket literal using RegEx?

前端 未结 6 1939
灰色年华
灰色年华 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:04

    In .Net you escape special characters by adding up a backslash; "\" meaning it would become; "["...

    Though since you normally do this in string literals you would either have to do something like this;

    @"\["
    

    or something like this;

    "\\["
    
    0 讨论(0)
  • 2021-02-07 01:06

    \] is correct, but note that PHP itself ALSO has \ as an escape character, so you might have to use \\[ (or a different kind of string literal).

    0 讨论(0)
  • 2021-02-07 01:08

    You don't need to escape it: if isolated, a ] is treated as a regular character.
    Tested with eregi_replace and preg_replace.

    [ is another beast, you have to escape it. Looks like single and double quotes, single or double escape are all treated the same by PHP, for both regex families.

    Perhaps your problem is elsewhere in your expression, you should give it in full.

    0 讨论(0)
  • 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 "\\]"

    0 讨论(0)
  • 2021-02-07 01:17

    Works flawlessly:

    <?php
        $hay = "ab]cd";
        echo eregi_replace("\]", "e", $hay);
    ?>
    

    Output:

    abecd
    
    0 讨论(0)
  • 2021-02-07 01:25

    You problem may come from the fact you are using eregi_replace with the first parameter enclosed in simple quotes:

     '\['
    

    In double quotes, though, it could works well depending on the context, since it changes the way the parameter is passed to the function (simple quotes just pass the string without any interpretation, hence the need to double to "\" character).

    Here, if "\[" is interpreted as an escape character, you still need to double "\".

    Note: based on your comment, you may try the regex

    <\s*(?:br|p)\s*\/?\s*\>\s*\[
    

    in order to detect a [ right after a <br>or a <p>

    0 讨论(0)
提交回复
热议问题