faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

15 of 16 people (94%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Do I have to escape square brackets in a regular expression?

Jun 30th, 1999 12:58
Nathan Wallace, Teo::home


The square brackets are used in a regular expression to denote a range
of possible characters.  For example:

    [gKe5] - will match any of g, K, e, 5
    [^gKe5] - will match any character other than g, K, e, 5

If you want to match a square bracket itself then you must escape it in
the regular expression.

    "\[" - will match the character [
    "\[\]" - will match the character [ then the character ]

One more example for clarity:

    "\[[gKe5][^gKe5]\]" - will match [; then one of g, K, e 5; then 
                          anything other than g, K, e, or 5; then the
                          character ]