Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9134253
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:37:40+00:00 2026-06-17T08:37:40+00:00

I need to remove all additional spaces in a string. I use regex for

  • 0

I need to remove all additional spaces in a string.
I use regex for matching strings and matched strings i replace with some others.
For better understanding please see examples below:

3 input strings:

Hello, how are you?
Hello , how are  you?
Hello     ,     how    are   you    ?

This are 3 strings that should match by one pattern-regex.
It looks something like this:

Hello\s*,\s+how\s+are\s+you\s*?

It works fine but there is a perfomance problem.
If I have a lot of patterns (~20k) and try to execute each pattern it runs very slow (3-5 minutes).

Maybe there is better way for doing this?
for example use some 3d-party libs?

UPD: Folks, this question is not about how to do this. It’s about how to do this with best perfomance. 🙂


Let me explain more detailed. The main goal is tokenize text. (replace some token with special symbols)

For example I have a token “nice try”.
Then I input text “this is nice try”.
result: “this is @tokenizedtext@” where @tokenizedtext@ some special symbols. It doesen’t matter in this case.

Next I have string “Mike said it was a nice try”.
result should be “Mike said it was a @tokenizedtext@”.
I think the main idea is clear.

So I can have a lot of tokens. When I process it I convert my token from “nice try” to pattern “nice\s+try”. and try to replace with this pattern input text.
It works fine. But if in tokens there is more spaces and there is also punctuation then my regexes became bigger and works very slow.

Do you have some suggestions (technical or logic) for solving this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:37:41+00:00Added an answer on June 17, 2026 at 8:37 am

    I can suggest a few solutions.

    First of all, avoid the static Regex method. Create an instance of it (and store it, don’t call the constructor for each replacement!) and, if possible, use RegexOptions.Compiled. It should improve your performance.

    Second, you can try to review your pattern. I’ll do some profiling, but I’m currently undecisive between:

    @"(?<=\s)\s+"

    With replacement being an empty string or:

    @"\s+"

    With a space as a replacement. You can try this code, in the meanwhile:

    var s = "Hello , how are  you?";
    var pattern = @"\s+";
    var regex = new Regex(pattern, RegexOptions.Compiled);
    var replaced = regex.Replace(s, " ");
    

    EDIT: After having done some measurement, the second pattern seems to be faster. I’m editing my sample to adapt it.

    EDIT 2: I’ve written an unsafe method. It’s much faster than the other ones presented here, including the Regex ones, but, as the word itself says, it’s unsafe. I don’t think that there’s any problem with the code I’ve written but I may be wrong — So please, check it again and again in case there’s a bug in the method.

    static unsafe string TrimInternal(string input)
    {
        var length = input.Length;
        var array = stackalloc char[length];
        fixed (char* fix = input)
        {
            var ptr = fix;
            var counter = 0;
            var lastWasSpace = false;
            while (*ptr != '\x0')
            {
                //Current char is a space?
                var isSpace = *ptr == ' ';
                //If it's a space but the last one wasn't
                //Or if it's not a space
                if (isSpace && !lastWasSpace || !isSpace)
                    //Write into the result array
                    array[counter++] = *ptr;
                //The last character (before the next loop) was a space
                lastWasSpace = isSpace;
                //Increase the pointer
                ptr++;
            }
            return new string(array, 0, counter);
        }
    }
    

    Usage (compile with /unsafe):

    var s = TrimInternal("Hello    , how       are     you?");
    

    Profiling made in Release build, optimizations on, 1000000 iterations:

    My above solution with Regex: 00:00:03.2130121

    The unsafe solution: 00:00:00.2063467

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm adding dynamically labels to hbox, and i need to remove all spaces between
I need to remove all classes of 'no-right-marg' on all #tips li elements. I
I need to remove all entries in a dictionary accordingly to a specified lower
I have a problem where I need to remove all code and triggers from
So I have these lines of javascript code that I need to remove all
In my application, _collection is a List from which I need to remove all
I have a large list [[1,.., ..],[2,...,...],[5,...,...],[1,...,...]] I need to remove all elements that
File: /home/USER/DIR/a http://www.here.is.a.hyper.link.net/ /home/USER/DIR/b http://www.here.is.another.hyper.link.net/ Need to remove all the odd lines in this
I need a way to remove ALL using statements from code and fully qualify
I need to remove the following script from my page(ASP.NET 3.5), leaving all other

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.