如何 Java 正则表达式匹配除指定模式之外的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18864509/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:44:46  来源:igfitidea点击:

How to Java Regex to match everything but specified pattern

javaregex

提问by vamsiampolu

I am trying to match everything but garbage values in the entire string.The pattern I am trying to use is:

我试图匹配整个字符串中除垃圾值之外的所有内容。我尝试使用的模式是:

    ^.*(?!\w|\s|-|\.|[@:,]).*$

I have been testing the pattern on regexPlanet and this seems to be matching the entire string.The input string I was using was:

我一直在 regexPlanet 上测试模式,这似乎与整个字符串匹配。我使用的输入字符串是:

    Vamsi///#k03@g!!!l.com 123**5

How can I get it to only match everything but the pattern,I would like to replace any string that matches with an empty space or a special charecter of my choice.

我怎样才能让它只匹配除模式之外的所有内容,我想替换与空白或我选择的特殊字符匹配的任何字符串。

采纳答案by Bernhard Barker

The pattern, as written, is supposed to match the whole string.

所写的模式应该匹配整个字符串。

^- start of string.
.*- zero or more of any character.
(?!\w|\s|-|\.|[@:,])- negative look-ahead for some characters.
.*- zero or more of any character.
$- end of string.

^- 字符串的开始。
.*- 零个或多个任何字符。
(?!\w|\s|-|\.|[@:,])- 某些角色的负面展望。
.*- 零个或多个任何字符。
$- 字符串的结尾。

If you only want to match characters which aren't one of the supplied characters, try simply:

如果您只想匹配不是提供的字符之一的字符,请尝试简单:

[^-\w\s.@:,]

[^...]is a negated character class, it will match any characters not supplied in the brackets. See thisfor more information.

[^...]是一个否定字符类,它将匹配括号中未提供的任何字符。有关更多信息,请参阅内容。

Test.

测试