簡體   English   中英

C#正則表達式無法匹配任何東西(可能是因為無法正確轉義字符)

[英]C# Regex Can't Match Anything (Probably because can't escape characters properly)

我制作了一個正則表達式模式並在此站點中進行了測試: http//rubular.com/

我正在將這個模式寫成該網站的第一個框。

<div class="product clearfix">\n+<div class="img">\n+<a href="(.*?)">\n+<img class="lazyload" id='.*' data-original="(.*?)" alt=".*" title="(.*?)" \/>

我把第二個盒子留空了。

我的正則表達式模式非常好地尊重這個網站。

但我不能讓它在C#中工作

我正在嘗試這個:

WebClient client = new WebClient();

string MainPage = client.DownloadString("http://www.vatanbilgisayar.com/cep-telefonu-modelleri/");

string ItemPattern = "<div class=\"product clearfix\">\\n+" +   //  <div class="product clearfix">\n
                "<div class=\"img\">\\n" +                  //  <div class="img">\n
                "+<a href=\"(.*?)\">\\n" +                  //  +<a href="(.*?)">\n
                "+<img class=\"lazyload\"" +                //  +<img class="lazyload"
                "id='.*' data-original=\"(.*?)\"" +         //  id='.*' data-original="(.*?)"
                "alt=\".*\" title=\"(.*?)\"\\/>";           //  alt=".*" title="(.*?)" \/>

MatchCollection matches = Regex.Matches(MainPage, ItemPattern);

foreach (Match match in matches)
{
    Console.WriteLine("Area Code:        {0}", match.Groups[1].Value);
    Console.WriteLine("Telephone number: {0}", match.Groups[2].Value);
    Console.WriteLine();
}

我只是逃脫了每一個“用\\。我真的不明白為什么它不起作用,這開始讓我發瘋...

您需要2層轉義序列。 你需要為c#轉義一次,再為regex語法轉義一次。

如果要轉義正則表達式的字符也必須轉義\\ ,所以你應該在正則表達式級別將轉換序列的\\更改為\\\\

對你的字符串中的每個\\使用兩個\\。 不計算你已經為報價做的逃避。 因為\\是一個轉義字符。 看起來主要是“\\ n”發生3次。

原始字符串:

"product clearfix">\n+<div class="img">\n+<a href="(.*?)">\n+<img class="lazyload" id='.*' data-original="(.*?)" alt=".*" title="(.*?)" \/

此外,您可以將其分解為多行。 c#忽略空格,所以只需關閉引號並在行尾添加“+”,繼續以另一個引號開頭。

C#字符串:

string ItemPattern = "<div class=\"product clearfix\">\\n" +   //  <div class="product clearfix">\n
                    "+<div class=\"img\">\\n" +                 //  +<div class="img">\n
                    "+<a href=\"(.*?)\">\\n" +                  //  +<a href="(.*?)">\n
                    "+<img class=\"lazyload\"" +                //  +<img class="lazyload"
                    "id='.*' data-original=\"(.*?)\"" +         //  id='.*' data-original="(.*?)"
                    "alt=\".*\" title=\"(.*?)\"\\/>";           //  alt=".*" title="(.*?)" \/>

如果你仍然有問題,可能還有其他錯誤,可能在RegEx.Match(mainPage,ItemPattern)中。 根據您所做的調試,聽起來字符串已成功創建,並且沒有MatchCollection。 所以它要么是你如何獲得比賽,要么是參考比賽。

暫無
暫無

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

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