jxie0755
jxie0755

Reputation: 1742

python regex for single or multiple empty endline

I know there will be easier way to do this, for example using endswith or even str.split('\n'). But I want to know how to use regex to find out if a text file has one/multiple/None empty lines at the end.

suppose I got the content by using content = f_obj.read()

I tried:

one_N = r'\S(\s{1})$'
multi_N = r'\S\s(\s+)$'

Doesn't seem to work.

Upvotes: 0

Views: 34

Answers (2)

Matt.G
Matt.G

Reputation: 3609

No Empty Line: (?<!\n)\Z - Demo

One Empty Line: (?<=(?<!\n)\n)\Z - Demo

More than one Empty Line: \n{2,}\Z - Demo

Upvotes: 2

ZZzzZZzz
ZZzzZZzz

Reputation: 1844

The regex solution to check for empty lines is below

if (line.matches("\\s*")) {
   print('Line is blank')
}

Upvotes: 1

Related Questions