我需要在第一次出现空格之前删除字符串中的所有内容。
- 每个字符串都以数字开头,后面跟一个空格
- 替换数字和空格,从而保留字符串的其余部分
例如:
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/