80

I tried this but it doesn't work :

[^\s-]

Any Ideas?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
rudimenter
  • 3,030
  • 4
  • 31
  • 44
  • 8
    @Marcelo The regex posted **works fine**. That was why I was asking. The only assumption I can make is that @rudimenter was expecting the class to repeat by default. – Yacoby May 07 '10 at 11:27
  • 2
    Yacoby, you should made that clear in the first place. – Marcelo Cantos May 07 '10 at 12:56
  • 1
    Hi rudimenter, can you please edit your question to clarify what you were actually asking? – Antonio Feb 17 '16 at 14:37

5 Answers5

134
[^\s-]

should work and so will

[^-\s]
  • [] : The char class
  • ^ : Inside the char class ^ is the negator when it appears in the beginning.
  • \s : short for a white space
  • - : a literal hyphen. A hyphen is a meta char inside a char class but not when it appears in the beginning or at the end.
codaddict
  • 429,241
  • 80
  • 483
  • 523
79

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

Engvard
  • 791
  • 5
  • 2
9

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

Cagdas
  • 819
  • 6
  • 5
  • \s stands for whitespace if you backslash the backslash it has an completly different meaning – rudimenter May 07 '10 at 11:33
  • 4
    @rudimenter: Cagdas was just suggesting that there might be different behavior depending on your environment (which you didn't tell us). – Dirk Vollmar May 07 '10 at 11:40
  • 11
    @rudimenter: If the regex is defined by a string, then you need to escape the backslash or use a verbatim string like `@"string"` in .NET or `r"string"` in Python. – Tim Pietzcker May 07 '10 at 11:44
7

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

Community
  • 1
  • 1
polygenelubricants
  • 364,035
  • 124
  • 554
  • 617
-6

Try [^- ], \s will match 5 other characters beside the space (like tab, newline, formfeed, carriage return).

RokL
  • 2,748
  • 3
  • 21
  • 23