简体   繁体   中英

Why does Regex.Match return only 1 result?

I'm using a regex that strips the href tags out of an html doc saved to a string. The following code is how I'm using it in my C# console app.

Match m = Regex.Match(htmlSourceString, "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']");

        if (m.Success)
        {
            Console.WriteLine("values = " + m);
        }

However, it only returns one result, instead of a list of all the href tags on the html page. I know it works, because when I trying RegexOptions.RightToLeft , it returns the last href tag in the string.

Is there something with my if statement that doesn't allow me to return all the results?

匹配方法搜索字符串的第一个出现, 匹配方法搜索所有出现的事件。

If you use Match instead of Match es you need to use a loop to get all the matches calling m.NextMatch() at the end of each loop. For example:

    Match m = Regex.Match(htmlSourceString, "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']");
    Console.Write("values = ");
    while (m.Success) 
    { 
        Console.Write(m.Value);
        Console.Write(", "); // Delimiter
        m = m.NextMatch();
    }
    Console.WriteLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM