-1

There is regular expression for finding blank string and I want only negation. I also see this question but it does not work for java (see examples). Solution also not work for me (see 3-rd line in example).

For example

Pattern.compile("/^$|\\s+/").matcher(" ").matches() - false
Pattern.compile("/^$|\\s+/").matcher(" a").matches()- false
Pattern.compile("^(?=\\s*\\S).*$").matcher("\t\n a").matches() - false

return false in both cases.

P.S. If something is not clear ask me questions.

UPDATED

I want to use this regular expression in @Pattern annotation without creating custom annotation and programmatic validator for it. That's why I want a "plain" regexp solution without using find function.

3 Answers 3

5

It's not clear what you mean by negation.

If you mean "a string that contains at least one non-blank character," then you can use this:

Pattern.compile("\\S").matcher(str).find()

If it's really necessary to use matches, then you can do it with this.

Pattern.compile("\\A\\s*\\S.*\\Z").matcher(str).matches()

This just matches 0 or more spaces followed by a non-space followed by any characters at all up to the end of the string.

If you mean "a string that is all non-blank with at least one such character," then you can use this:

Pattern.compile("\\A\\S+\\Z").matcher(str).matches()

You need to study the Java regex syntax. In Java, regular expressions are compiled from strings, so there's no need for special delimiters like /.../ or %r{...} as you'll see in other languages.

7
  • Congratulations to your 10k! Aug 21, 2013 at 12:11
  • Pattern.compile("\\S").matcher("abc").matches() - false, but must be true. Your solution is only for 1 character in the string.
    – Cherry
    Aug 22, 2013 at 2:24
  • 2
    @Cherry Use find instead of match. I edited the answer to make this explicit.
    – Gene
    Aug 22, 2013 at 2:34
  • 1
    @Cherry Then what do you mean by negation? The opposite of a string of all spaces is a string that is not all spaces, which is a string that contains at least one non-space. That's what I gave you the regex for...
    – Gene
    Aug 22, 2013 at 2:42
  • The main reason why I added this question is possibility to use @Pattern to ckeck that input string is not blank. So I do not want to use find() function. I can create my own annotation and write a validator, but I asked to check is there solution in "plain" rexexp or not.
    – Cherry
    Aug 27, 2013 at 4:32
1

How about this:

if(!string.trim().isEmpty()) {
    // do something
}
2
0

Use regex \s : A whitespace character: \t\n\x0B\f\r.

Pattern.compile("\\s")
1
  • Works only for string with 1 character.
    – Cherry
    Aug 27, 2013 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.