Results 1 to 4 of 4

Thread: How to use regex to remove whitespace in C#

  1. #1
    Join Date
    Jun 2009
    Posts
    404

    How to use regex to remove whitespace in C#

    I am having a small piece of code that displays a line after each statement. I want to remove this unnecessary extra lines. I thought regex would be the best solution for this. But now the problem is the that I don't know how to use regex in C#? Does anyone over here know about this? Please help!

  2. #2
    Join Date
    Nov 2008
    Posts
    996

    Re: How to use regex to remove whitespace in C#

    Here is how regex is used:
    Code:
    string str1 = your_string;
    Regex regex = new Regex(@"\W");
    string newString = regex.Replace(str1, " ");
    Console.WriteLine (newString);

  3. #3
    Join Date
    May 2008
    Posts
    685

    Re: How to use regex to remove whitespace in C#

    You can even try out the code as below:

    Code:
    public static string RemoveWhitespace (this string myStr)
    {
        try
        {
            return new Regex(@"\s*").Replace(myStr, string.Empty);
        }
        catch (Exception)
        {
            return myStr;
        }
    }

  4. #4
    Join Date
    May 2008
    Posts
    2,297

    Re: How to use regex to remove whitespace in C#

    Well is what I did it once:

    Code:
    using System;
    using System.Text.RegularExpressions;
    
    class MainClass
    {
        static void Main()
        {
            string s1 = "My name   is Zecho.";
            Regex r1 = new Regex(@"\s+");
            string s2 = r1.Replace(s1, @" ");
            Console.WriteLine(s2);
            Console.ReadLine();
        }
    }
    Output of the code would be as follows:

    My name is Zecho.

Similar Threads

  1. Substring with a regex
    By TechGate in forum Software Development
    Replies: 5
    Last Post: 02-04-2010, 11:06 AM
  2. How to remove leading whitespace from each line?
    By Conraad in forum Software Development
    Replies: 5
    Last Post: 23-02-2010, 10:14 PM
  3. Regex string with quotes
    By Gunner 1 in forum Software Development
    Replies: 5
    Last Post: 07-02-2010, 06:03 AM
  4. Regex with xml tag
    By Vodka in forum Software Development
    Replies: 5
    Last Post: 04-02-2010, 02:11 AM
  5. Query in php regex
    By Linux-Us in forum Software Development
    Replies: 5
    Last Post: 14-12-2009, 12:54 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,714,145,820.50924 seconds with 16 queries