Sebbeleu
Sebbeleu

Reputation: 45

Match newlines except if it ends with semicolon

I want to match newline \n except when the line ends with semicolon. My attempt so far is (?!;\n)\n which matches newline but doesn't exclude anything. Sample text:

this is a line of text that should match
it should exclude this line;
this line should also be ignored;
but this should match

Upvotes: 3

Views: 1695

Answers (3)

Vorsprung
Vorsprung

Reputation: 34377

use a negated character class

.*[^;]$

This matches the lines as the test data implies. To match exactly the newline at the end of the line only as a capture

.*[^;](\n)

Here is a demo in perl showing this behaviour, assuming the testdata is in a file textdata.txt

perl -n -e 'print ord($1)."yes line $. $1" if /.*[^;](\n)/; ' nlmadness.txt 
10yes line 1 
10yes line 4 

The "ord($1)" expression means convert the $1, the first match from a character to a numeric encoding. On my system this is UTF-8 and newline matches to decimal ten

The $. is the line number

Upvotes: 6

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

To only match a \n not preceded with ; in Notepad++, you can use

\n(?<!;\n)

or

(?<!;)\n

See regex demo

The (?<!...) is a look-behind zero-width assertion that checks but does not consume the text that is immediately before the text we match (the \n symbol). You tried a look-ahead that checks the text right after the text you matched.

The same construct in Vim is \(....\)\@<!:

\n\(;\n\)\@<!

or

\(;\)\@<!\n

Upvotes: 4

Jan
Jan

Reputation: 43169

Bind it to the beginning and the end:

^(.*[^;]{1})$
# match everything from star to end (^ to $)
# the last character MUST NOT be a semicolon
# save the whole string in a capturing group

See a demo here on regex101.com.

Upvotes: 1

Related Questions