[英]Cut a line out of a string with Regex
我正在尋找一種從C#中的字符串中刪除第2行的解決方案。 當然,我可以逐行閱讀,但是使用正則表達式,它會更好,更優雅。 舉個例子:
之前:
this is line 1
this is line 2
this is line 3
this is line 4
后:
this is line 1
this is line 3
this is line 4
有人對Regex如何執行此操作有很好的提示嗎? 謝謝。
你可以用正則表達式做,如果你真的想:
s = Regex.Replace(s, @"\A(.*\n).*\n", "$1");
對於處理平台相關的行尾:
Regex regex = new Regex(string.Format(@"\A(.*{0}).*{0}", Environment.NewLine));
s = regex.Replace(s, "$1");
但是我認為使用string.Split
然后重新加入會更清楚:
List<string> lines = s.Split(new string[]{ Environment.NewLine },
StringSplitOptions.None)
.ToList();
lines.RemoveAt(1);
// Note: In .NET 4.0 the ToArray call is not required.
string result = string.Join(Environment.NewLine, lines.ToArray());
我同意正則表達式更為簡潔,但是對正則表達式語法不熟悉的人(甚至是對正則表達式語法不熟悉的人)都希望使用更明確的版本。
我知道您要求使用正則表達式解決方案,但是當我說正則表達式不是此工作的正確工具時,請不要開槍。
您可以通過將文件讀取為行並跳過第二個文件來獲得一個優雅的解決方案:
string fileContents =
String.Join(Environment.NewLine, File.ReadAllLines("filepath").Where((line, index) => index != 1));
將正則表達式設置為“單行模式”以禁用將換行符視為特殊字符。 例:
Regex r = new Regex(@"^[^\r\n]*\r\n([^\r\n]*\r\n)", RegexOptions.Singleline);
Match m = r.Match(myText);
String line 2 = null;
if (m.Success) {
line2 = m.Captures[1].Value;
myText = substring(myText, 0, m.Captures[1].Index) +
substring(myText, m.Captures[1].Index + m.Captures[1].Length);
}
// line2 will contain "this is line 2\r\n"
// myText will be all text except line2.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.