Regex help !!!

Posted on 2007-10-17
Last Modified: 2010-04-15
Hi you experts.

Suppose i have the following string : "         99       MyData                "
I need a regular expression that will trim all spaces(spaces and tabs) and only puts one space between them like this : "99 MyData" .

Thank you all in advance.
Question by:adktd
    LVL 27

    Expert Comment

    I would first "trim" the string with one of the built-in functions in whichever string library you have loaded, then regex replace \s+ with \s to condense the multiple consecutive spaces into individual spaces.
    LVL 1

    Author Comment

    Can you provide me with an example so i can test it?
    LVL 13

    Accepted Solution

            string s = "         99       MyData                ";
             string result = Regex.Replace(s,@"(^\s+)|(\s+$)","");
             result = Regex.Replace(result,@"\s+"," ");

    The first replace removes spaces at the start and end of the line.

    The second replaces multiple consecutive spaces with a single space.

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    730 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now