71

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.

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

conceptSeeker
  • 729
  • 1
  • 7
  • 7

4 Answers4

107

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
12

First of all, you don't need a regexp. Simply call 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 = "[^=]*";
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 8
    This may be very helpful for the original poster. But this answer is very far from the specific text of the question, which leads thousands of others to this page. This alternative has much less value for them. – ctpenrose Mar 11 '19 at 16:55
9

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

String patternString = "[^=]*";
Chetter Hummin
  • 6,687
  • 8
  • 32
  • 44
3

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

if str.indexOf('=')  //...
Josh
  • 8,082
  • 5
  • 43
  • 41
moodywoody
  • 2,149
  • 1
  • 17
  • 21
  • 9
    `contains` is shorter, easier to understand, and you don't need to fiddle around with indices. – phihag Mar 19 '12 at 13:21