locked
Remove blank lines from a textbox RRS feed

  • Question

  • Blank lines in a textbox can be:
    A series of spaces followed by a carriage return OR
    A carriage return OR
    A line filled with tabs

    How can I remove all blank lines from the text entered in my textbox ?
    Wednesday, November 15, 2006 5:55 PM

Answers

  • textBox1.Text = Regex.Replace(textBox1.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)","${Text}\r\n");

    does the trick. OmegaMan, thanks for your time & patience!
    Thursday, December 7, 2006 5:09 PM

All replies

  • you could try doing a trim:

    this.theTextBox.Text = this.theTextBox.Text.Trim();

    this will trim the start and end of a textbox text and removes any whitespaces. Is this what you are after?

    Wednesday, November 15, 2006 6:34 PM
  • This works great to remove leading/trailing spaces at the start and end of the textbox.

    If text is entered in blocks like paragraphs - is there any way to clean up extra spaces/lines and reassemble the paras with a single lines between them ?

    Something like a split with cleanup and then reassemble.
    Wednesday, November 15, 2006 6:47 PM
  • not quite. I guess you could go through each line, see if there is a new line and replace all newlines in that line with just 1 newline

     

    for (int counter = 0; counter < theTextBox.Lines.Length - 1; counter++)

       if (theTextBox.Lines[counter].Contains(Environment.NewLine))

       {

          theTextBox.Lines[counter] = theTextBox.Lines[counter].Replace(Environment.NewLine, Environment.NewLine);

          //replace all newlines in this current line with just a singular newline

       }

    }

     

    something like this? The other way I guess would be to have a keydown event, check the key pressed in the textbox, if its an Enter key, get the current line (Lines.Length - 1) and check the previous line - if that also contains a newline then handle the event and ignore it (e.Handled = true I think)

    Wednesday, November 15, 2006 6:52 PM
  • very interesting approach. Thanks.

    Is there any way to get rid of blank lines with tabs in it ?
    Wednesday, November 15, 2006 7:21 PM
  • not sure about that one really. if its before and after the sentence then the trim() will work but if its within the string, not sure about that one. I guess you could just do a replace on " " with " " and see how that goes (blank whitespace).

    I can't remember if "\t" will work (tab)..so.... string.replace("\t", " ");

    Wednesday, November 15, 2006 7:24 PM
  • Easy to do with Regular Expressions:

          // Remove trailing blanks
          textBox1.Text = Regex.Replace(textBox1.Text, "\\s+\r\n", "\r\n");
          // Remove duplicate end-of-lines
          textBox1.Text = Regex.Replace(textBox1.Text, "\r\n\r\n", "\r\n");

    The 1st one replaces one or more (+) white space characters (\s) followed by a end-of-line (\r\n) by end-of line.

    The 2nd one replaces a double end-of-line with a single end-of-line.
    Wednesday, November 15, 2006 7:42 PM
  • interesting...

                this.textBox1.Text = Regex.Replace(textBox1.Text , "\t", "");
                this.textBox1.Text = Regex.Replace(textBox1.Text,"\r\n\r\n","\r\n");

    seems to work for the overall textbox.

    Now how can I store each para into an aray ?
    Wednesday, November 15, 2006 7:43 PM
  • of course. Duh..reading too much into it. yeh thats much better
    Wednesday, November 15, 2006 7:46 PM
  • Thanks. That's great regex.

    The problem with the above is that
    If the text is in paragraph blocks - it rips out the blank line dividing paras.

    I'd like to rip out extra tabs, whitepaces-before-newline, double-blank-lines and preserve paras with a single blank line between them.

    And then take each para and store it into an array...

    Wednesday, November 15, 2006 7:48 PM
  • Jeez, you sure like your answers on a silver platter.  Split half your salary with me and I'll think about it.  If that sounds like a bad deal, I'm sure you can figure it out from what was given...
    Wednesday, November 15, 2006 8:06 PM
  • Silver platter indeed. If you look earlier in the thread you will see that I figured out some regex myself.

    I'm not paid a salary for coding and I think these forums are to help those who are learning. So let's quit the flaming. If you don't want to reply, just don't.
    Wednesday, November 15, 2006 8:59 PM
  • Sorry I have came to this post kinda late...Here is the regex answer to the secondary run to remove double blank lines but not the paragraph line

    (?<Text>.*)(?:[\r\n]?(?:\r\n)?)

    with the replacement regex of

    ${Text}

    Run this with the flags of Multiline and Ignore case. If that fails, add the flag Explicit capture. (The tool I used to test is on a 1.1 version of .Net, hence I mention that).

    The first part captures all items except for the newline and places it into the named group Text. The second match will keep a return or new line (not both) if it exists and one following line but ignore a combination pattern for two blank lines. Its subtle....

    IMHOI am not saying that what NoBugz said was right....but he has always been a stand up guy for me and I think he was just having a bad day.

    The situation reminded me of was a movie quote from the Kubrick's Full Metal Jacket set during the Vietnam war. There was a scene where the main character, Joker, meets up with a tough combat veteran, Animal Mother, and begins to exchange words with him. As things heat up to a possible confrontation a third party person steps up to move back Animal and says this to Joker:

     8-Ball wrote:
    You might not believe it, but under fire Animal Mother is one of the finest human beings in the world. All he needs is somebody to throw hand-grenades at him the rest of his life.


    That is what comes to my mind. I don't mean to feed the fire or offend anyone...
    Thursday, November 30, 2006 3:55 PM
  • Now there's some interesting input. Thanks Omegaman.

    So if I had a 'dirty' textbox and a cmdCleanParasbutton, how would I replace textbox1.text with cleaned paras using your regex ? Would you be able to show me your code ?
    Monday, December 4, 2006 7:59 PM
  • I would do what nobugz did, but for the second regex replace use my regexe's on the button event...or am I missing something?

    It is a two step process and NoBugz had the methodology right.
    Monday, December 4, 2006 10:40 PM
  • Thanks. I'm having a time trying to figure out how to use the regex. Appreciate any help !

    private void button1_Click(object sender, EventArgs e)
            {
           // Remove trailing blanks
          textBox1.Text = Regex.Replace(textBox1.Text, "\\s+\r\n", "\r\n");
          textBox1.Text = Regex.Replace(textBox1.Text, "?<Text>.*)(?:[\r\n]?(?:\r\n)?");   //gives me an error
            }
    Tuesday, December 5, 2006 9:59 PM
  • Missing a ( in the regex use this line

    textBox1.Text = Regex.Replace(textBox1.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?");

    When one is working with RegExes it is good to use a tool to parse the regex'es outside the code here are two tools I use:

    RadSoft's Free Regular Expression Designer
    Expresso by UltraPico

    Thursday, December 7, 2006 3:50 PM
  • Thanks for that correction and for the links to the great tools. In the codeline above the match evaluator is missing. So I added it.

    Here's the amended code:

    private void button1_Click(object sender, EventArgs e)
    {
    // Remove trailing blanks
    textBox1.Text = Regex.Replace(textBox1.Text, "\\s+\r\n", "\r\n");
    textBox1.Text = Regex.Replace(textBox1.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?","\r\n");
    }


    I was still getting an error "System.ArgumentException was unhandled
    Message="parsing \"(?<Text>.*)(?:[\r\n]?(?:\r\n)?\" - Not enough )'s."

    So I used Expresso & realised the regex should be :
    textBox1.Text = Regex.Replace(textBox1.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)","\r\n");

    Running the code wipes all the text out of the textbox. I'm not sure what I'm doing wrong.

    Thursday, December 7, 2006 4:09 PM
  • textBox1.Text = Regex.Replace(textBox1.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)","${Text}\r\n");

    does the trick. OmegaMan, thanks for your time & patience!
    Thursday, December 7, 2006 5:09 PM
  • I tried the expression in the previous post and found that, whilst it was a start to removing blank lines, it was insuffficient for my requirements. I wanted to remove every line that contained only whitespace (this might be one or more space characters  or one or more tab characters or a combination thereof. I also wanted to remove any blank lines at the start of the text and any blank lines at the end.

    I would like to think that this all be could be done with a single regular expression but my expertise is not up to it. Therefore, I ended up with the following C# function which seems to do all that I require.

            /**
             * Given a String, remove all empty lines.
             *
             * Parameters:
             * - text : the String from which blank lines are ro be removed.
             *
             * Returns:
             * The modified text.
             */
            private String removeBlankLines( String text )
            {
                // Remove all tabs characters
                String retText = text.Replace("\t", " ");

                // If the first one or more lines are blank, remove them
                retText = Regex.Replace(retText, "(?<Text>.*)(?:(^\u0020*\r\n)(\u0020*\r\n\u0020*)*)", "${Text}");

                // Replace all occurrences of muliple new lines to single newlines
                retText = Regex.Replace(retText, "(?<Text>.*)(?:(\u0020*\r\n\u0020*){2,})", "${Text}\r\n");

                // Remove any trailing new lines or white space
                retText = Regex.Replace(retText, "(?<Text>.*)(?:(\u0020*\r\n)(\u0020*\r\n\u0020*)*$)", "${Text}");

                return retText;
            }

    Thursday, February 12, 2009 1:26 PM
  • You should post your requirements as a new thread in the .Net Regular Expressions forum. I think someone might be able to create a regex pattern which might do it.

    If you post, provide example text and the expected result.

    William Wegerson (www.OmegaCoder.Com)
    Thursday, February 12, 2009 2:24 PM
  • Following done it for me:

    Regex.Replace(text, @"(\r\n)?(^\s*$)+", "", RegexOptions.Multiline);

     

    Friday, April 9, 2010 4:47 PM
  • Adrian,

    Out of all of examples on this thread. The only thing that worked in Visual C# 2010 is your removeBlankLines function. Together with a .ToString().TrimStart(' ').TrimEnd(' ') at the end.

    My requirement was that member of staff were required to copy a block of text from an email and paste it into a text control. As the text was used to generate an activation code I could not afford for there to be any trailing spaces or carriage returns. The above finally did it.

    Thanks.


    • Edited by Nadim J Saturday, September 10, 2011 9:12 AM
    Saturday, September 10, 2011 9:09 AM
  • you could try doing a trim:

    this.theTextBox.Text = this.theTextBox.Text.Trim();

    this will trim the start and end of a textbox text and removes any whitespaces. Is this what you are after?

    Thanks so much, this worked for me.
    Friday, August 9, 2013 6:49 PM
  • can somebody help me to remove the blank spaces between the Textbox. My requirement is 

           Textbox1    Value

           Textbox2    Value

           Textbox3    Value

    So if the TextBox2 Value is not found then hide it and remove that empty space. So the output should look like

           

            Textbox1   Value

            Textbox3   Value

    The values are coming from the XML.
    • Edited by Sam437 Tuesday, July 31, 2018 3:32 PM
    Tuesday, July 31, 2018 3:25 PM