Java 使用正则表达式匹配除 = 之外的任何字符

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

Using regex to match any character except =

javaregex

提问by conceptSeeker

I am trying to write a String validation to match any character (regular, digit and special) except =.

我正在尝试编写一个字符串验证来匹配除 = 之外的任何字符(常规、数字和特殊)。

Here is what I have written -

这是我写的——

    String patternString = "[[^=][\w\s\W]]*";
    Pattern p = Pattern.compile(patternString);
    Matcher m = p.matcher(str);

    if(m.matches())
        System.out.println("matches");
    else
        System.out.println("does not");

But, it matches the input string "2009-09/09 12:23:12.5=" with the pattern.

但是,它将输入字符串 "2009-09/09 12:23:12.5=" 与模式匹配。

How can I exclude = (or any other character, for that matter) from the pattern string?

如何从模式字符串中排除 = (或任何其他字符,就此而言)?

回答by tripleee

If the only prohibited character is the equals sign, something like [^=]*should work.

如果唯一禁止的字符是等号,则[^=]*应该可以使用类似的字符。

[^...]is a negated character class; it matches a single character which is any character except one from the list between the square brackets. *repeats the expression zero or more times.

[^...]是一个否定字符类;它匹配单个字符,该字符是方括号之间列表中的任何字符除外。*重复表达式零次或多次。

回答by moodywoody

If you only want to check for occurence of "=" why don't you use the String indexOf() method?

如果您只想检查“=”的出现,为什么不使用 String indexOf() 方法?

if str.indexOf('=')  //...

回答by phihag

First of all, you don't need a regexp. Simply call contains:

首先,您不需要正则表达式。只需致电contains

if(str.contains("="))
    System.out.println("does not");
else
    System.out.println("matches");

The correct regexp you're looking for is just

您正在寻找的正确正则表达式只是

String patternString = "[^=]*";

回答by Chetter Hummin

If your goal is to not have any = characters in your string, please try the following

如果您的目标是在字符串中不包含任何 = 字符,请尝试以下操作

String patternString = "[^=]*";