views:

99

answers:

3

Hi

I want to creat a regular expression for strings which uses special characters '[' and ']'.

Value is "[action]".

Expression I am using is "[\\[[\\x00-\\x7F]+\\]]".

I tried doing it by adding "\\"before '[' and ']'.

But it doesn't work.

Can any one help me with this.

thanks

-devSunday

A: 

Just stick one backslash before the square bracket.

Two backslashes escapes itself, so the regex engine sees \[, where [ is a special char.

Charlie Somerville
This is a Java string literal, so he needs double backslashes in order for the "regex engine" to see a single backslash.
Laurence Gonsalves
Ah right, my bad, I guess I'm used to typing regexes in a C# verbatim string.
Charlie Somerville
+3  A: 

You probably want to remove the enclosing brackets "[]". In regexps they mean a choice of one of the enclosed characters

Dmitry
Like this, it would seem: "\\[[\\x00-\\x7F]+\\]".
Gunslinger47
+1  A: 

Two backslashes before the open and close brackets: \\[ and \\]

The double backslash evaluates a single backslash in the string. The single backslash escapes the brackets so that they are not interpreted as surrounding a character class.

No backslashes for the brackets that do declare the character class: [a-z] (you can you any range you like, not just a to z)

The Kleene star operator matches any number of characters in the range.

public class Regexp {
    public static void main(final String... args) {
        System.out.println("[action]".matches("\\[[a-z]*\\]"));
    }
}

On my system:

$ javac Regexp.java && java Regexp
true
Greg Mattes