I am building a string of last names separated by hyphens. Sometimes a whitespace gets caught in there. I need to remove all whitespace from end result.
Sample strin
Instead of a RegEx
use Replace
for something that simple:
LastName = LastName.Replace(" ", String.Empty);
No need for regex. This will also remove tabs, newlines etc
var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));
WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000
.
Regex.Replace
does not modify its first argument (recall that strings are immutable in .NET) so the call
Regex.Replace(LastName, @"\s+", "");
leaves the LastName
string unchanged. You need to call it like this:
LastName = Regex.Replace(LastName, @"\s+", "");
All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.
Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.
new string
(stringToRemoveWhiteSpaces
.Where
(
c => !char.IsWhiteSpace(c)
)
.ToArray<char>()
)
OR
new string
(stringToReplaceWhiteSpacesWithSpace
.Select
(
c => char.IsWhiteSpace(c) ? ' ' : c
)
.ToArray<char>()
)
Why use Regex when you can simply use the Trim() method
Text='<%# Eval("FieldDescription").ToString().Trim() %>'
OR
string test = "Testing ";
test.Trim();
Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"
if (!string.IsNullOrEmpty(url))
{
string origFileName = Path.GetFileName(url);
string modiFileName = origFileName.Trim().Replace(" ", "~");
url = url.Replace(origFileName , modiFileName );
}
return url;