regexp中是否有(!)运算符?

我需要删除给定字符串中的所有字符,除了应该留下的几个字符。 如何用regexp做到这一点?

简单测试:不应删除字符[1,a,*],所有其他字符应来自字符串“asdf123 **”。

在集合中有:^。

你应该能够做到这样的事情:

text = text.replaceAll("[^1a*]", ""); 

完整样本:

 public class Test { public static void main(String[] args) { String input = "asdf123**"; String output = input.replaceAll("[^1a*]", ""); System.out.println(output); // Prints a1** } } 

[]内使用时, ^ (插入符号)是非运算符。

它使用如下:

 "[^abc]" 

这将匹配除bc之外的任何字符。

有一个否定的字符类 ,可能适用于此实例。 您可以通过将^放在类的开头来定义一个,例如:

[^1a\*]

针对您的具体情况。

在字符类中,^不是。 所以

[^1a\*]将匹配除那些之外的所有字符。

您希望匹配除[asdf123 *]之外的所有字符,请使用^

在Java正则表达式中没有像Perl中那样的“not”运算符。