Java regular expression matching no carriage return followed by a linefeed

前端 未结 1 1139
孤独总比滥情好
孤独总比滥情好 2020-12-12 05:24

I\'ve tried (^\\r)\\n but this doesn\'t work.

How do you do this?

(I appreciate that in Java-like code you need to use (^\\\\r)\\\\n

相关标签:
1条回答
  • 2020-12-12 05:45

    Depending on your requirements:

    • [^\r]\n - linefeed that is preceded with any character but a carriage return. This means there must be a character before the linefeed and two symbols will be matched.
    • (?<!\r)\n - linefeed that is not preceded with a carriage return. This means there only newline symbol will get matched and \r will only be tested for presence (as (?<!\r) is a negative lookbehind, a zero-width assertion that does not consume any text, but returns true if the pattern inside it is absent right before the current position in the string).

    For a demo, please check these two links:

    • At regex101.com, (?<!\r)\n is matching as linebreaks are pure \n at the Web site
    • At regexstorm.net, the same pattern does not match anything as linebreaks are \r\n there.
    0 讨论(0)
提交回复
热议问题