changed
changed

Reputation: 2143

java regular expression , how to add '[' to expression

I want to create 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.

Upvotes: 0

Views: 5753

Answers (3)

Greg Mattes
Greg Mattes

Reputation: 33959

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

Upvotes: 1

Dmitry
Dmitry

Reputation: 3780

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

Upvotes: 3

user47322
user47322

Reputation:

Just stick one backslash before the square bracket.

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

Upvotes: 0

Related Questions