P45 Imminent
P45 Imminent

Reputation: 8591

Java regular expression matching no carriage return followed by a linefeed

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)

Thank you,

Upvotes: 2

Views: 1833

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

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:

Upvotes: 4

Related Questions