93

I tried this but it doesn't work :

[^\s-]

Any Ideas?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
rudimenter
  • 3,242
  • 4
  • 33
  • 46
  • 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

6 Answers6

149
[^\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
  • 445,704
  • 82
  • 492
  • 529
87

It can be done much easier:

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

Engvard
  • 871
  • 6
  • 2
10

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

Cagdas
  • 819
  • 6
  • 6
  • \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
8

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
  • 376,812
  • 128
  • 561
  • 623
0

Note that regex is not one standard, and each language implements its own based on what the library designers felt like. Take for instance the regex standard used by bash, documented here: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03_05. If you are having problems with regular expressions not working, it might be good to simplify it, for instance using "[^ -]" if this covers all forms of whitespace in your case.

-6

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

RokL
  • 2,663
  • 3
  • 22
  • 26