[英]C# Replace Everything before the first Space
我需要在第一次出現空格之前刪除字符串中的所有內容。
例如:
22印度的貓
殿下
562吃土豆
第二個冰箱里有42個餅干
2564尼亞加拉瀑布在下午2點
我只需要:
印度的貓
殿下
吃土豆
第二個冰箱里的餅干
尼亞加拉瀑布在下午2點
基本上刪除第一個空格之前的每個數字,包括第一個空格。
我試過這個:
foreach (string line in lines)
{
string newline = line.Trim().Remove(0, line.IndexOf(' ') + 1);
}
這適用於低於10的數字。在它達到2位數后,它無法正常工作。
我該如何更改代碼?
如果要確保只匹配字符串開頭的數字,可以使用以下正則表達式:
^\d+\p{Zs}
見演示
聲明如下:
public static readonly Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled);
^\\d+\\p{Zs}
正則表達式意味着:字符串開頭的一個或多個數字后跟1個空格。
然后像使用它一樣
string newline = rx.Replace(line, string.Empty);
編輯 :為了確保該line
沒有前導空格,我們可以添加.Trim()
來剝離它像:
Regex rx = new Regex(@"^\d+\p{Zs}", RegexOptions.Compiled);
string newline = rx.Replace(line.Trim(), string.Empty);
另一種方案:
var lines = new string[]
{
"22 The cats of India",
"4 Royal Highness",
"562 Eating Potatoes",
"42 Biscuits in the 2nd fridge",
"2564 Niagara Falls at 2 PM"
};
foreach (var line in lines)
{
var newLine = string.Join(" ", line.Split(' ').Skip(1));
}
我知道你已經找到了解決問題的方法。 但我將解釋為什么你的代碼首先不起作用。
您的數據有額外的空格,這就是您修剪它的原因: line.Trim()
。 但真正的問題在於以下聲明:
string newline = line.Trim().Remove(0, line.IndexOf(' ') + 1);
您正在假設操作的順序以及string
數據類型不是不可變的這一事實。 當Trim()
函數的操作完成時,它返回一個在Remove()
操作中使用的全新字符串。 但是IndexOf()
函數是在原始數據行上完成的。
所以正確的代碼行如下:
foreach (string line in lines)
{
// trim the line first
var temp = line.Trim();
// now perform all operation on the new temporary string
string newline = temp.Remove(0, temp.IndexOf(' ') + 1);
// debugging purpose
Console.WriteLine(newline);
}
像這樣使用正則表達式:
string newline = Regex.Replace(line, @"^\s*\d+\s*", "");
這將僅刪除數字,而不是第一個空格之前的其他文本。
這就是你要找的東西
foreach (string line in lines)
{
string newline = line.Replace(line.Split(new Char[]{' '})[0] + ' ',string.Empty);
}
UPDATE
string search=line.Split(new Char[]{' '})[0];
int pos=line.indexOf(search);
string newline = line.Substring(0, pos) + string.Empty + line.Substring(pos + search.Length);
完整的代碼
using System;
public class Program
{
public static void Main()
{
var lines = new string[]
{
"22 The cats of India",
"4 Royal Highness",
"562 Eating Potatoes",
"42 Biscuits in the 2nd fridge",
"2 Niagara Falls at 2 PM"
};
foreach(string line in lines){
string search=line.Split(new Char[]{' '})[0];
int pos=line.IndexOf(search);
string newline = line.Substring(0, pos) + string.Empty + line.Substring(pos + search.Length);
Console.WriteLine(newline);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.