Dodi
Dodi

Reputation: 2269

pattern matcher

I have the following pattern matcher.

 Pattern pat = Pattern.compile("[^a-z][^,.:;]");

How do I include the ] character itself in it ?

Upvotes: 1

Views: 441

Answers (5)

Eduardo
Eduardo

Reputation: 697

The standard way is the use of quote function of the Pattern class. This function return the literal pattern String for the specified String.

String myLiteralString = Pattern.quote(",.[:;");
Pattern pat = Pattern.compile("[^a-z][^" + myLiteralString + "]");

This method escape all special characters of the regular expression syntax.

Upvotes: 0

Rodrigo Sasaki
Rodrigo Sasaki

Reputation: 7226

You don't really need to escape it. There is a special rule in Regular Expressions, where if you want the actual ] character in your list, it has to be the first element on it. And it'll work just fine. Give this code a try:

public static void main(String[] args){
    String texto = "[]hello[]";
    Pattern p = Pattern.compile("[]]+");
    Matcher m = p.matcher(texto);
    while(m.find()){
        System.out.println(m.group());
    }
}

Upvotes: 0

eatSleepCode
eatSleepCode

Reputation: 4637

You can do it by using escape character \ like this \\].

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

] is a special character used to denote the end of a character class so it needs to be escaped:

Pattern pat = Pattern.compile("[^a-z][^,.:;\\]]");

Upvotes: 5

hvgotcodes
hvgotcodes

Reputation: 120178

You need to escape it.

\\]

See this.

Upvotes: 5

Related Questions