Reputation: 2269
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
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
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
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