Remove all whitespace from C# string with regex

前端 未结 7 1563
遇见更好的自我
遇见更好的自我 2020-12-25 10:18

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

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 10:51

    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.

提交回复
热议问题