Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm looking for a way to remove all spaces " " from a string with the exeption of the text inside paratheses ..

Obviosuly there are ways of doing this by copying and replacing portions of the text, but I beleive there has to be an "easier"- cleaner way by using regex - I just can't figure it out..

sample String :

Remove all spaces from this (Don't remove spaces from this) Again remove spaces

This should look like this after applying the regex.replace

Removeallspacesfromthis(Don't remove spaces from this)Againremovespaces


any Ideas :-)
Posted

If you can make sure that there are no nested parenthsis, you can do it in Regex. Otherwise you can not.

E.g. in C#:
C#
string input = "Remove all spaces from this (Don't remove spaces from this) Again remove spaces";
string output = Regex.Replace(input, @"\s*(\(.*?\)|\S+)\s*", "$1");
Console.WriteLine(input);
Console.WriteLine(output);


This results in
Remove all spaces from this (Don't remove spaces from this) Again remove spaces
Removeallspacesfromthis(Don't remove spaces from this)Againremovespaces


Cheers
Andi
 
Share this answer
 
Comments
Kenneth Haugland 15-Aug-12 9:48am    
Better a5 :)
Andreas Gieriet 15-Aug-12 10:09am    
Thanks, Kenneth!
Yes, use balanced grouping:
In Depth with .NET RegEx Balanced Grouping[^]

BTW: Here is a great tool for constructing and deconstructing RegEx patterns:
Expresso - A Tool for Building and Testing Regular Expressions[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900