我需要匹配不属于以下字符集的字符:
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z. 0 1 2 3 4 5 6 7 8 9 / - ? :()。 ,'+ space
要做到这一点,我正在使用这个正则表达式:
String regex = "[^\\da-zA-Z/\\-\\?:\\(\\)\\.\\,'\\+ ]+";
不幸的是,这不起作用。
我也试过了(否定):
String regex = "(?![\\da-zA-Z/\\-\\?:\\(\\)\\.\\,'\\+ ]+)";
但是不行。
任何人都可以提供帮助吗?
答案 0 :(得分:7)
我认为您不能在其他字符类中使用预定义的字符类,例如\d
。此外,您逃离的大多数角色在角色类中并不特殊(尽管逃逸应该是无害的)。所以:
String regex = "[^0-9a-zA-Z/\\-?:().,'+ ]+";
旁注:在你的问题中,你说你想要替换’
(一个奇特的撇号撇号),但在正则表达式中你只有一个普通的撇号'
。如果需要,请改变它。
这是一个测试:
public class RegTest {
public static final void main(String[] args) {
String regex, test, result;
// First, test without the negation and make sure it *does* replace the target chars
regex = "[0-9a-zA-Z/\\-?:().,'+ ]+";
test = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+";
result = test.replaceAll(regex, "%");
System.out.println(result);
// Prints %
// Now, test *with* the negation and make sure it matches other characters (I put
// a few at the beginning) but not those
regex = "[^0-9a-zA-Z/\\-?:().,'+ ]+";
test = "[@!\"~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+";
result = test.replaceAll(regex, "%");
System.out.println(result);
// Prints %abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+
}
}