(遇到同樣情況的人請注意,這個問題可能是.net和C#指定的。請參閱下面Wiktor的回答。)
在問這個問題之前,我已經閱讀了許多相關的問題(包括:匹配換行符 - \n 或 \r\n?),但這些答案都不起作用。
就我而言,我想洗掉某些代碼檔案中的所有 // 注釋。要處理 Mac、Unix、Windows 中的檔案,我需要一些東西來匹配 // 和 /r、/n 或 /r/n 之間的文本。
下面是代碼檔案的測驗內容:
var text = "int rn = 0; //comment1.0\r\n"
"int r = 0; //comment2.\r"
"int n = 0; //comment3.\n"
"end";
var txt = RemoveLineEndComment();
這是正則運算式(如果您不是 C 語言專家,請只關注正則運算式):
public static class CommentRemover
{
private static readonly Regex RegexRemoveLineEndComment =
new(@"\/\/.*$", RegexOptions.Multiline);
public static string RemoveLineEndComment(this string text)
{
var t = RegexRemoveLineEndComment.Match(text).Value;
return RegexRemoveLineEndComment.Replace(text, string.Empty);
}
}
我需要的是 txt = "int rn = 0; \r\nint r = 0; \rint n = 0; \nend"。以下是正則運算式和相應的結果:
//.*$ => txt="int rn = 0; \nint r = 0; \nend"(缺少int n = 0)
//.*(?=\r\n) => txt="int rn = 0; \r\nint r = 0; //comment2.\rint n = 0; //comment3.\nend" (comment2 and還剩3個)
//.*(?=\r?\n?) => txt="int rn = 0; \nint r = 0; \nend"(缺少 int n = 0)
//.*(?=(\r\n|\r|\n)) => txt="int rn = 0; \nint r = 0; \nend"(缺少int n = 0)
//.*(?=[\r\n|\r|\n]) => txt="int rn = 0; \nint r = 0; \nend"(缺少 int n = 0)...
\r 似乎有問題,無法識別。如果我只使用 \r\n,正則運算式“//.*(?=\r\n)”適用于下面的測驗內容:
var text = "int rn = 0; //comment1.0\r\n"
"int r = 0; //comment2.\r\n"
"int n = 0; //comment3.\r\n"
"end";
有人幫我嗎?謝謝你的幫助。
uj5u.com熱心網友回復:
在 .NET 中,.模式匹配回車 (CR) 字符。它匹配除 LF 字符以外的任何字符。
請注意,沒有選項或修飾符可以重新定義此.行為。
因此,您可以使用
var RegexRemoveLineEndComment = new Regex(@"//[^\r\n]*", RegexOptions.Multiline);
請參閱C# 演示。
如果您還想洗掉 之前的空格,請在模式開始處//添加\s*(任何空格)或[\p{Zs}\t]*(水平空格)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334563.html
上一篇:帶有If條件問題的正則運算式
