Match whitespace but not newlines

后端 未结 6 1363
忘掉有多难
忘掉有多难 2020-11-22 15:57

I sometimes want to match whitespace but not newline.

So far I\'ve been resorting to [ \\t]. Is there a less awkward way?

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 16:31

    The below regex would match white spaces but not of a new line character.

    (?:(?!\n)\s)
    

    DEMO

    If you want to add carriage return also then add \r with the | operator inside the negative lookahead.

    (?:(?![\n\r])\s)
    

    DEMO

    Add + after the non-capturing group to match one or more white spaces.

    (?:(?![\n\r])\s)+
    

    DEMO

    I don't know why you people failed to mention the POSIX character class [[:blank:]] which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).

    DEMO

提交回复
热议问题