How to create a negated charclass pattern?
I need a method taking a patte开发者_StackOverflowrn as an argument and returning the negated pattern. The input pattern is always a charclass (otherwise it'd impossible). The straightforward attempt
public Pattern negate(Pattern p) {
return Pattern.compile("[^" + p.pattern() + "]");
}
private void test() {
final Pattern p = Pattern.compile("[a-z]");
final Pattern n = negate(p);
System.out.println(n.matcher("0").matches());
}
fails because of [
in [^[
(unlike in [^xyz[
) being taken literally instead of as a start of a nested charclass.
You can't nest character classes like that.
If you always know that you're getting a character class, the easiest way would be to trim the input string of its brackets:
public Pattern negate(Pattern p) {
return Pattern.compile("[^" + p.pattern().substring(1));
}
A more robust method would be to parse the input with regular expresions... :)
精彩评论