Java 正则表达式中有 not (!) 运算符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3866279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a not (!) operator in regexp?
提问by Roman
I need to remove all characters from the given string except for several which should left. How to do that with regexp?
我需要从给定的字符串中删除所有字符,除了几个应该留下的字符。如何用正则表达式做到这一点?
Simple test: characters[1, a, *] shouldn't be removed, all other should from string "asdf123**".
简单测试:不应删除字符[1, a, *],所有其他字符都应来自字符串“asdf123**”。
采纳答案by Jon Skeet
There is: ^ in a set.
集合中有:^。
You should be able to do something like:
您应该能够执行以下操作:
text = text.replaceAll("[^1a*]", "");
Full sample:
完整样本:
public class Test
{
public static void main(String[] args)
{
String input = "asdf123**";
String output = input.replaceAll("[^1a*]", "");
System.out.println(output); // Prints a1**
}
}
回答by jjnguy
When used inside [
and ]
the ^
(caret) is the not
operator.
时所使用的内部[
和]
所述^
(脱字符号)是not
操作员。
It is used like this:
它是这样使用的:
"[^abc]"
That will match any character except for a
b
or c
.
这将匹配除a
b
or之外的任何字符c
。
回答by eldarerathis
There's a negated character class, which might work for this instance. You define one by putting ^
at the beginning of the class, such as:
有一个否定的字符类,它可能适用于这个实例。您可以通过放置^
在类的开头来定义一个,例如:
[^1a\*]
[^1a\*]
for your specific case.
对于您的具体情况。
回答by Cfreak
In a character class the ^ is not. So
在字符类中, ^ 不是。所以
[^1a\*]
would match all characters except those.
[^1a\*]
将匹配除那些字符之外的所有字符。
回答by user318904
You want to match against all characters except: [asdf123*], use ^
您想匹配除 [asdf123*] 之外的所有字符,请使用 ^
回答by Steve Emmerson
There's no "not" operator in Java regular expressions like there is in Perl.
Java 正则表达式中没有像 Perl 中那样的“非”运算符。