使用正则表达式从C#字符串中删除所有空格 [英] Remove all whitespace from C# string with regex

查看:62
本文介绍了使用正则表达式从C#字符串中删除所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立由连字符分隔的姓氏字符串.有时,空白会陷入其中.我需要从最终结果中删除所有空格.

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.

要处理的示例字符串:

安德森-里德·史密斯

Anderson -Reed-Smith

它必须以(Anderson之后没有空格)结尾:

It needs to end up as (no space after Anderson):

安德森·里德·史密斯

Anderson-Reed-Smith

姓氏字符串在字符串变量LastName中.

The last name string is in a string variable, LastName.

我正在使用正则表达式:

I am using a regular expression:

Regex.Replace(LastName, @"[\s+]", "");

其结果是:

安德森-里德·史密斯.

Anderson -Reed-Smith.

我也尝试过:

Regex.Replace(LastName, @"\s+", "");

Regex.Replace(LastName, @"\s", "");

我在做什么错了?

推荐答案

代替 RegEx ,使用 Replace 进行简单的操作:

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

这篇关于使用正则表达式从C#字符串中删除所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆