Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 25-08-2009
Member
 
Join Date: Jun 2009
Posts: 403
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!
Reply With Quote
  #2  
Old 25-08-2009
Member
 
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);
Reply With Quote
  #3  
Old 25-08-2009
Member
 
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;
    }
}
Reply With Quote
  #4  
Old 25-08-2009
Member
 
Join Date: May 2008
Posts: 2,293
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:

Quote:
My name is Zecho.
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: , ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "How to use regex to remove whitespace in C#"
Thread Thread Starter Forum Replies Last Post
Substring with a regex TechGate Software Development 5 02-04-2010 11:06 AM
How to remove leading whitespace from each line? Conraad Software Development 5 23-02-2010 10:14 PM
Regex string with quotes Gunner 1 Software Development 5 07-02-2010 06:03 AM
Regex with xml tag Vodka Software Development 5 04-02-2010 02:11 AM
Query in php regex Linux-Us Software Development 5 14-12-2009 12:54 PM


All times are GMT +5.5. The time now is 04:28 PM.