Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match a square bracket literal using RegEx?

Tags:

string

regex

php

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 ]...

like image 865
aalaap Avatar asked Dec 08 '08 10:12

aalaap


People also ask

How do you match square brackets in regex?

You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

What is [] in regular expression?

The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a [] . It provides a range construct. The regex [a-z] will match any letter a through z.

How do you match a literal parenthesis in a regular expression?

The way we solve this problem—i.e., the way we match a literal open parenthesis '(' or close parenthesis ')' using a regular expression—is to put backslash-open parenthesis '\(' or backslash-close parenthesis '\)' in the RE. This is another example of an escape sequence.


2 Answers

\] 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).

like image 115
Michael Borgwardt Avatar answered Sep 23 '22 05:09

Michael Borgwardt


Works flawlessly:

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

Output:

abecd 
like image 21
Bombe Avatar answered Sep 25 '22 05:09

Bombe