Home > Enterprise >  Regex: string can contain spaces, but not only spaces. It cannot contain `*` nor `:` characters eith
Regex: string can contain spaces, but not only spaces. It cannot contain `*` nor `:` characters eith

Time:11-14

I need help finding a regex that will allow most strings, except:

  • if the string only contains whitespaces
  • if the string contains : or *

I want to reject the following strings:

  • "hello:world"
  • "hello*world"
  • " " (just a whitespace)

But the following strings will pass:

  • "hello world"
  • "hello"

So far, I can accomplish what I want... in two patterns.

  • [^:*]* rejects the 2 special characters
  • .*\S.* rejects any string with only whitespaces

I'm not sure how to combine these two patterns into one...

I'll be using the regex pattern along with Java.

CodePudding user response:

An example of how you could combine your two patterns for use with the matches method:

"[^:*]*[^:*\\s][^:*]*"

[^\s] is equivalent to \S.

CodePudding user response:

You could use a negative lookahead:

^(?!\s*$)[^:*] $
  • ^ - start of string anchor
  • (?!\s*$) negative lookahead rejecting whitespace-only strings
  • [^:*] - one or more of any character except : and *
  • $ - end of string anchor

Demo

  • Related