What is the Regular Expression For “Not Whitespace and Not a hyphen”

前端 未结 5 823
既然无缘
既然无缘 2020-12-03 04:18

I tried this but it doesn\'t work :

[^\\s-]

Any Ideas?

相关标签:
5条回答
  • 2020-12-03 04:45

    It can be done much easier:

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

    0 讨论(0)
  • 2020-12-03 04:45

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

    0 讨论(0)
  • 2020-12-03 04:52
    [^\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.
    0 讨论(0)
  • 2020-12-03 04:56

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

    0 讨论(0)
  • 2020-12-03 05:02

    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

    • Regular expressions and escaping special characters
    • regular-expressions.info/Character class
      • Metacharacters Inside Character Classes

        The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret.

    0 讨论(0)
提交回复
热议问题