locked
Remove blank lines from a textbox RRS feed

  • Pytanie

  • 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 ?
    środa, 15 listopada 2006 17:55

Odpowiedzi

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

    does the trick. OmegaMan, thanks for your time & patience!
    czwartek, 7 grudnia 2006 17:09

Wszystkie odpowiedzi

  • 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?

    środa, 15 listopada 2006 18:34
  • 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.
    środa, 15 listopada 2006 18:47
  • 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)

    środa, 15 listopada 2006 18:52
  • very interesting approach. Thanks.

    Is there any way to get rid of blank lines with tabs in it ?
    środa, 15 listopada 2006 19:21
  • 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", " ");

    środa, 15 listopada 2006 19:24
  • 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.
    środa, 15 listopada 2006 19:42
  • 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 ?
    środa, 15 listopada 2006 19:43
  • of course. Duh..reading too much into it. yeh thats much better
    środa, 15 listopada 2006 19:46
  • 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...

    środa, 15 listopada 2006 19:48
  • 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...
    środa, 15 listopada 2006 20:06
  • 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.
    środa, 15 listopada 2006 20:59
  • 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...
    czwartek, 30 listopada 2006 15:55
  • 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 ?
    poniedziałek, 4 grudnia 2006 19:59
  • 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.
    poniedziałek, 4 grudnia 2006 22:40
  • 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
            }
    wtorek, 5 grudnia 2006 21:59
  • 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

    czwartek, 7 grudnia 2006 15:50
  • 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.

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

    does the trick. OmegaMan, thanks for your time & patience!
    czwartek, 7 grudnia 2006 17:09
  • 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;
            }

    czwartek, 12 lutego 2009 13:26
  • 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)
    czwartek, 12 lutego 2009 14:24
  • Following done it for me:

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

     

    piątek, 9 kwietnia 2010 16:47
  • 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.


    • Zmodyfikowany przez Nadim J sobota, 10 września 2011 09:12
    sobota, 10 września 2011 09:09
  • 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.
    piątek, 9 sierpnia 2013 18:49
  • 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.
    • Zmodyfikowany przez Sam437 wtorek, 31 lipca 2018 15:32
    wtorek, 31 lipca 2018 15:25