什么是“ Not Whitespace and Not a hyphen”的正则表达式

我试过了,但是没有用:

[^\s-]

有什么想法吗?

267388 次浏览
[^\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.

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

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

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

It can be done much easier:

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

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.