簡體   English   中英

C#regEx表達式與換行符不匹配

[英]C# regEx expression not matching newline

這是我的文件test1.txt

Line 4:   http://go34.microsoft.com/fwlink/p/?LinkId=333333
    Line 4:   http://go/p.microsoft.com/fwlink/p/?LinkId=333333

我想編寫一個與此處列出的2個URL相匹配的正則表達式。 這是我正在使用的regEx表達式

string pattern = "http://go.*?.microsoft.com/fwlink.*?[\r\n]";

我希望比賽如下:

http://go34.microsoft.com/fwlink/p/?LinkId=333333
http://go/p.microsoft.com/fwlink/p/?LinkId=333333

我只是無法獲得匹配的內容,無法弄清為什么不匹配。 相同的正則表達式可在notepad ++中使用。 不知道我在做什么錯。 有人可以幫忙嗎?

string pattern = "http://go.*?.microsoft.com/fwlink.*?$";

var urls = Regex.Matches(text, pattern,RegexOptions.Multiline)
            .Cast<Match>()
            .Select(m => m.Value.Trim())
            .ToList();

嘗試Regex.IsMatch(input, @"\\s*http://go\\S*\\.microsoft.com/fwlink\\S*\\s*", RegexOptions.Multiline) 這將匹配僅包含您的網址並由任意數量的空格字符包圍的任何行。

Regex.Repalce(input, @"\\s*(http://go.*\\.microsoft.com/fwlink\\S*)\\s*", "$1", RegexOptions.Multiline)將僅獲取匹配的URL。

嘗試這個:

//note the @ at the beginning
string pattern = @"http://go.*?.microsoft.com/fwlink.*?[\r\n]";

也許在文件末尾需要一個空白行(按Enter)? 您的文件實際上以\\ r \\ n結尾嗎?

也許您的字符串只是以換行符 aka “ \\ n”而不是回車換行符 aka “ \\ r \\ n”結束 ,也許您可​​以在正則表達式的末尾嘗試使用\\r?\\n

另外,可以將$ metacharacter與[^]結合使用,以匹配除換行以外的任何內容,例如:

string pattern = "http://go.*?.microsoft.com/fwlink[^$+]"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM