Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match last line break in file

In my quest to learn flex I'm having a scanner echo input adding line numbers.

After every line I display a counter and increment it.

Trouble is there is always a lone line number at the end of the display.

I need a regex that will ignore all line breaks except for the last one.

I tried [\n/<<EOF>>] to no avail.

Any thoughts?

like image 877
MayNotBe Avatar asked Oct 21 '25 23:10

MayNotBe


1 Answers

I don't know what regex engine uses Flex but you can use this regex:

\z

Working demo

\z assert position at the very end of the string.

Matches the end of a string only. Unlike $, this is not affected by multiline mode, and, in contrast to \Z, will not match before a trailing newline at the end of a string.

enter image description here

If above regex doesn't work then you can use this one:

(?<=[\S\s])$

Working demo

Edit: since flex seems to work slightly different than other regex engines you could use this regex:

[\s\S]$

To get the latest character of each line. Then you can iterated over all lines until get the last one. Here you have an online flex regex engine tool:

http://ryanswanson.com/regexp/#start

enter image description here

like image 150
Federico Piazza Avatar answered Oct 27 '25 06:10

Federico Piazza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!