C# 替换第一个空格之前的所有内容

标签 c# regex replace

我需要在第一次出现空格之前删除字符串中的所有内容。

  1. 每个字符串都以数字开头,后面跟一个空格
  2. 替换数字和空格,从而保留字符串的其余部分

例如:

22 The cats of India

4 Royal Highness

562 Eating Potatoes

42 Biscuits in the 2nd fridge

2564 Niagara Falls at 2 PM

我只需要:

The cats of India

Royal Highness

Eating Potatoes

Biscuits in the 2nd fridge

Niagara Falls at 2 PM

基本上删除第一个空格之前的所有数字,包括第一个空格。

我试过这个:

foreach (string line in lines)
{
       string newline = line.Trim().Remove(0, line.IndexOf(' ') + 1);
}

这适用于 10 以下的数字。达到 2 位数后,它就无法正常工作。

我应该如何更改我的代码?

最佳答案

如果要确保只匹配字符串开头的数字,可以使用以下正则表达式:

^\d+\p{Zs}

参见 demo

声明如下:

public static readonly Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled);

^\d+\p{Zs} 正则表达式表示:字符串开头的一位或多位数字后跟 1 个空格。

然后像这样使用它

string newline = rx.Replace(line, string.Empty);

编辑:为确保没有前导空格,我们可以添加.Trim()来去除它:

Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled);
string newline = rx.Replace(line.Trim(), string.Empty);

关于C# 替换第一个空格之前的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241014/

相关文章:

java - 我正在尝试使用具有多行的扫描仪,并尝试使用另一个字符串 java 更改输入

php - 使用 PHP 和 Regex 替换所有域名(包括子域名)

string - 用空值替换空字符串

c# - 如何使用 ASP.NET MVC 5.0 的 ASP.NET Identity 实现密码重置?

c# - 我如何区分 C# 中列表中的项目

regex - Perl:将字符添加到行的开头

regex - 使用正则表达式查找匹配项 - perl

c# - jQuery 加载 txt 文件 .html()

c# - 扩展方法 - 装饰者模式

regex - 包含除下划线外的一个特殊字符的密码强度正则表达式