We help IT Professionals succeed at work.

RegEx -- Delete Spaces at Beginning of Line, and Empty Lines

GivenRandy asked
Medium Priority
Last Modified: 2012-06-22
I have some original text that I am filtering using RegEx. Most stuff works like normal, but I'm having a hard time simulating a Trim() and also deleting empty lines. I want to use RegEx for this approach (i.e., not split and trim). In the following the "\r\n" is the standard ControlChars.CrLf characters.

 originalText = "\r\nSecond line.\r\n Third line, with leading space.\r\n\r\nFifth line.\r\n"

I can remove the double CrLf in the middle:

 cleanedText = Regex.Replace(originalText, "\r\n\r\n", ControlChars.CrLf)

But, how about the first one?

How about deleting the extra space in front of "Third line".

Looking for generic approach, not just for this example.
Watch Question

Distinguished Expert 2017
Hi GivenRandy;

This should do what you want.

        Dim originalText As String = vbCrLf & "Second line." & vbCrLf & _
            "  Third line, with leading space." & vbCrLf & _
            vbCrLf & "Fifth line." & vbCrLf
        Dim cleanedText As String = Regex.Replace(originalText, _
            "^(?<1>\r\n)*(?<2>\s*)(?<3>[^\r]+)(?<4>\r\n)*", _
            "$3" & vbCrLf, RegexOptions.Multiline)


Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
i just use mystring.trim and trimend to accomplish this
Fernando SotoRetired
Distinguished Expert 2017

Hi gangwisch;

GivenRandy also wants to remove all blank line from with in the string as well as leading spaces on lines with in the string. So then he would have to split the string loop through the array remove blank lines and make sure there is only one set of CrLf at the end of the line. The Regex will do it in one step.



Seems to work. Did you find a particular tool and/or book to be helpful? I know the basics of Regex, but need to improve.
Fernando SotoRetired
Distinguished Expert 2017

Hi GivenRandy;

Sorry but I have not found any good book on regular expressions. When I started working with Regex in .Net I used a program called the Regulator. This program is available for download at http://sourceforge.net/projects/regulator/ . Since then I have written my own and have been using it, a project that I am still working on.

Good luck;

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.