Triming leading and trailing new lines with regex.

Here is some regex to trim leading/trailing newlines carriage and spaces returns from some text.

Without replacing 'spaces' just new lines/carriage returns.
^(\n|\r)+|(\n|\r)+\Z
 
This will trim also spaces
^(\n|\r|\s)+|(\n|\r|\s)+\Z

Quick explanation might be in order. This regex consists of two parts, first one start at the beginning of the the line and follows consuming ‘\n’ or ‘\r’ one ore more times. Second part consumes ‘\n’ or ‘\r’ one or more times followed by end of input string or new line.

Example Input


        
 
Some text bla



More text after some breaks in between.






Output

Some text bla



More text after some breaks in between.

Leave a Comment

Your email address will not be published. Required fields are marked *