locked
Remove spaces in a string RRS feed

  • Question

  • User1632102518 posted

    How to remove all the spaces in a string except one..?

    For Example: if user enters "FirstName     LastName", in this case I need to remove all the spaces except one ie I need output as "FirstName LastName".

    Thanks for all the help.

    Tuesday, February 3, 2015 4:10 PM

Answers

  • User-434868552 posted

    @pka246

    You need to read the O.P.:  "How to remove all the spaces in a string except one..?"

    Your code could be tweaked, but it still fails to be comprehensive.

    Console.WriteLine("[" + Regex.Replace("  Firstname     Lastname   ", @"\s+", " ") + "]"); //  [ Firstname Lastname ]
    

    Note the untrimmed spaces.

    String fullname = "      Firstname       Lastname     ";
    fullname.Replace("  ", " ");
    Console.WriteLine("[" + fullname + "]");

    output still has all the spaces:

    [      Firstname       Lastname     ]

    Assignment is necessary with String.Replace"

    fullname = fullname.Replace("  ", " ");
    Console.WriteLine("[" + fullname + "]");

    However, this is still flawed because multiple spaces are left behind because String.Replace lacks reduction:

    [   Firstname    Lastname   ]
     ^^^         ^^^^        ^^^

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 4, 2015 3:37 AM
  • User-271186128 posted

    Hi sreeja1234,

    1.Data entered in the field must be letters of the alphabet, hyphens (-), apostrophes (‘), numbers (0-9), @ symbol, or blanks spaces () only.

    2.When the user has entered two or more consecutive spaces,When the user proceeds,Then the system will delete all consecutive spaces except one.

    As for this issue, I suppose you could try to use Regex.replace() method two times. For the first time, you could replace the characters (Such as: hyphens (-), apostrophes (‘), numbers (0-9), @ symbol) to the blanks spaces. Then, you can use this method remove all the spaces except one.

    Here is a sample, you could refer to it.

                string str1 = "AAA  999@@@--'''99  BBB";
    
                TextBox1.Text = Regex.Replace(Regex.Replace(str1, @"[0-9]|@|-|'+", " "), @"\s+", " ");
    

    The output: AAA BBB

    Best Regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 4, 2015 6:48 AM

All replies

  • User1632102518 posted

    Got it.


    string returnString = Regex.Replace(s, @"\s+", " ");

    Tuesday, February 3, 2015 4:12 PM
  • User1632102518 posted

    Not sure, how to use as a regular expression...can some one help please...

    [RegularExpression(@"^["\s+", " "]*$")] like this I need...

    Tuesday, February 3, 2015 4:19 PM
  • User-431565850 posted

    You probably don't want to put the validation in the viewmodel like that. It will just annoy the user. Instead, you can just call Trim() on the input string before you save it. You could also use the regex if you want, but Trim() will do the same thing.

    Edit: My Bad. I didn't completely read your question. I see they are entering their first and last name on one field. Use the regex before you save it. However, it would be much better for you to just give them 2 separate fields to enter their name in.

    Tuesday, February 3, 2015 4:23 PM
  • User1632102518 posted

    @jiveabillion

    I am validating it only on the server. Then ,the user will have option of entering the name with any number of spaces,once clicks on Save button, my code with throw modelvalidation errors based on the Reqularexpression I apply on the Model object.

    Tuesday, February 3, 2015 4:27 PM
  • User-431565850 posted

    Ok, then your validation expression needs to be what matches a string that is GOOD.

    Tuesday, February 3, 2015 4:34 PM
  • User-431565850 posted

    Here is one that will probably work. It isn't as clean as I would expect it to be, but it seems to work:

    ^[a-zA-Z]{1,44}\s{0,1}[a-zA-Z]{0,44}$

    You can test it here http://regexr.com/3abie

    This one should allow for names like Bob O'Malley or Jan Levinson-Gould :

    ^[a-zA-Z'-]{1,44}\s{0,1}[a-zA-Z'-]{0,44}$

    Tuesday, February 3, 2015 4:43 PM
  • User281315223 posted

    The RegularExpression Validator indicates the string that you want to accept (e.g. what is valid) and it will consider anything else invalid. Basically, you could simply indicate that you didn't want to allow any strings with repeating spaces :

    [RegularExpression(@"(?!.*\s{2,}.*)^.*$")]

    This should not allow any string that has two or more spaces in it and should accept anything else. Additionally though you are probably better off by either splitting these into two explicit fields or by using a single field and performing your replace within your server-side code.

    Tuesday, February 3, 2015 5:04 PM
  • User-431565850 posted

    Rion, your regex allows a space after the last name.

    Tuesday, February 3, 2015 5:07 PM
  • User281315223 posted

    Rion, your regex allows a space after the last name.

    I didn't notice that was one of the requirements of it. You could resolve it by not allowing the string to begin or end with a space :

    [RegularExpression(@"(?!.*\s{2,}.*|^\s.*|.*\s$)^.*$")]

    Tuesday, February 3, 2015 5:13 PM
  • User-434868552 posted

    @sreeja1234     TIMTWOTDI

    QUESTION:  have you considered having TWO textboxes?

    one for the first name

    one for the last name

    imho, that is the way to go ... then you simply .TRIM the field.

    End users often do not read carefully ... so when you let them use a single field, you risk

    John Smith
        John Smith
    John  Smith
    Smith, John
    Mr. John Smith

    et cetera




    Tuesday, February 3, 2015 5:24 PM
  • User1632102518 posted

    @RIon,

    Thanks for the reply. My main requirement is I have EmployeeName textbox in the UI where the user will enter his firstName & LastName in the same control. So, using regular expressions I need to do the following validation for the same property.

    1.Data entered in the field must be letters of the alphabet, hyphens (-), apostrophes (‘), numbers (0-9), @ symbol, or blanks spaces () only.

    2.When the user has entered two or more consecutive spaces,When the user proceeds,Then the system will delete all consecutive spaces except one.

    How I can provide these 2 validations using a single ReqularExpression to my Model Property.Upto now, my model property is as follows..

     [RegularExpression(@"^[A-Za-z0-9''('')' @-]*$", ErrorMessage = "This field can only contain letters, numbers, hyphens, spaces, or apostrophes.")]

     public string EmployeeName { get; set; }

    Tuesday, February 3, 2015 5:29 PM
  • User-431565850 posted

    That's what I was saying before. You can't do both. Just sanitize the input before you save it by using the regex to remove spaces between the names and Trim() to remove them at the end. I still think it would be better for you to use two textboxes though.

    What you are asking is like saying "HEY! You can't put your name in like that, but we'll fix it for you. THIS TIME" Laughing

    The problem here is that there is no event or anything to hook into after the model validation fires to allow you to sanitize the data, so you need to just sanitize it before you save it.

    Tuesday, February 3, 2015 5:32 PM
  • User1632102518 posted

    Somehow the page design is like that which I have to validate it as how it is designed. Thanks for all your valuable replies, I will try discussing the same risks with my architect.

    Tuesday, February 3, 2015 5:54 PM
  • User-434868552 posted

    @sreeja1234

    again, i ask, why do you not have two fields?

    regex expressions are not necessarily the best solution.

    to paraphrase Paul Linton, if you need to use regex to solve a problem, you likely now have two problems.

    There are many valid first names and last names.  Examples:

    • Alejandro G. Iñárritu
    • Ellen Goosenberg Kent 
    • Elizabeth Yianni-Georgiou
    • Jóhann Jóhannsson
    • Martin Hernández
    • Frank A. Montaño
    • Dan DeLeeuw
    • Johann Gottfried Hübner
    • August Sallé
    • Adam Bøving
    • Nguyễn Tấn Dũng
    • Võ Nguyên Giáp
    • Sinéad O'Connor

    et cetera

    Tuesday, February 3, 2015 5:59 PM
  • User1632102518 posted

    @gerrylowry,

    We are saving the Name to only one column in the backend,not to 2 different columns.So , having one control in the UI will suffice my requirement.

    But,still I am not the person who designed the screen .

    Tuesday, February 3, 2015 6:28 PM
  • User281315223 posted

    sreeja1234

    How I can provide these 2 validations using a single ReqularExpression to my Model Property.Upto now, my model property is as follows..

     [RegularExpression(@"^[A-Za-z0-9''('')' @-]*$", ErrorMessage = "This field can only contain letters, numbers, hyphens, spaces, or apostrophes.")]

    Firstly, Regular Expression Validation on it's own isn't going to be able to accomplish this. One thing that you could consider doing to make the process a bit easier would be to simply wire up a Javascript event on the change or blur events for your TextBox which would perform the appropriate replacement as seen below :

    <!-- Your Example TextBox -->
    <asp:TextBox ID="ExampleTextBox" Text=" FirstName     LastName " onblur='CleanUpSpaces(this);' onchange='CleanUpSpaces(this);' />
    <script type='text/javascript'>
        function CleanUpSpaces(source){
            // Remove any duplicate spaces and trim it
            source.value = source.value.replace(/\s+/gi,' ').trim();
        }
    </script>

    You can see a working example here. Additionally, you could handle actually validating your input through a client-side regular expression as well (as it never hurts to have both client and server-side validation).

    Tuesday, February 3, 2015 8:34 PM
  • User-434868552 posted

    @sreeja1234

    [sreeja1234 is] not the person who designed the screen

    imho, your designer ought to realize that one can have two fields on the screen and then concatenate them on the backend.  FWIW

    Tuesday, February 3, 2015 8:53 PM
  • User-1461986491 posted

    You need to use Regular expression to remove whitespace from string...Its fast..

    Regex.Replace("Hello World!", @"\s+", ""); //HelloWorld!

    You can also use Replace method:

    string hello = "Hello World!";
    hello.Replace("  ", String.Empty);

    Tuesday, February 3, 2015 11:54 PM
  • User-434868552 posted

    @pka246

    You need to read the O.P.:  "How to remove all the spaces in a string except one..?"

    Your code could be tweaked, but it still fails to be comprehensive.

    Console.WriteLine("[" + Regex.Replace("  Firstname     Lastname   ", @"\s+", " ") + "]"); //  [ Firstname Lastname ]
    

    Note the untrimmed spaces.

    String fullname = "      Firstname       Lastname     ";
    fullname.Replace("  ", " ");
    Console.WriteLine("[" + fullname + "]");

    output still has all the spaces:

    [      Firstname       Lastname     ]

    Assignment is necessary with String.Replace"

    fullname = fullname.Replace("  ", " ");
    Console.WriteLine("[" + fullname + "]");

    However, this is still flawed because multiple spaces are left behind because String.Replace lacks reduction:

    [   Firstname    Lastname   ]
     ^^^         ^^^^        ^^^

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 4, 2015 3:37 AM
  • User-271186128 posted

    Hi sreeja1234,

    1.Data entered in the field must be letters of the alphabet, hyphens (-), apostrophes (‘), numbers (0-9), @ symbol, or blanks spaces () only.

    2.When the user has entered two or more consecutive spaces,When the user proceeds,Then the system will delete all consecutive spaces except one.

    As for this issue, I suppose you could try to use Regex.replace() method two times. For the first time, you could replace the characters (Such as: hyphens (-), apostrophes (‘), numbers (0-9), @ symbol) to the blanks spaces. Then, you can use this method remove all the spaces except one.

    Here is a sample, you could refer to it.

                string str1 = "AAA  999@@@--'''99  BBB";
    
                TextBox1.Text = Regex.Replace(Regex.Replace(str1, @"[0-9]|@|-|'+", " "), @"\s+", " ");
    

    The output: AAA BBB

    Best Regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 4, 2015 6:48 AM
  • User1632102518 posted

    Thanks all for all your valuable inputs.

    What I finally decided is to have Regex to remove additional spaces except one and RegularExpression to implement the first Validation.

    Wednesday, February 4, 2015 8:59 AM