使用正则表达式查找字符串中某个模式的所有匹配项

时间:2018-06-07 19:28:14

标签: c# regex

所以我是正则表达式的新手,我已经成功地在我的项目中使用它,但只找到一个特定的匹配。

现在我试图在html源代码中找到某个url模式的所有匹配项。

网址是这样的:

链接示例1:https://clips.twitch.tv/KindYummyCarrotPeteZaroll?tt_content=video_thumbnail

链接示例2:https://clips.twitch.tv/AmericanOilyMeerkatSaltBae?tt_content=video_thumbnail

我有这段代码搜索链接:

       MatchCollection matches = Regex.Matches(source, @"^(https://clips.twitch.tv/)+(.*?)+(video_thumbnail)$");

        if (matches.Count <= 0)
        {
            MessageBox.Show(matches.Count.ToString() + " urls found");
        }
        else
        {
            MessageBox.Show(matches.Count.ToString() + " urls");
        }

我的第一个问题是源字符串在某种程度上是错误的,所以我在这个字符串中尝试了这个正则表达式:

string source = (" adsfgsdfg adsfg assdfg https://clips.twitch.tv/KindYummyCarrotPeteZaroll?tt_content=video_thumbnail dfgsdfgszdfg asdfg https://clips.twitch.tv/AmericanOilyMeerkatSaltBae?tt_content=video_thumbnailsadfgdf g");

我也试过这个正则表达式:

Regex.Matches(source, @"^(https://clips.twitch.tv/)+([a-z0-9A-Z]{1,100})+(\?)+(tt_content=video_thumbnail)$");

但结果总是找到0个网址。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你的正则表达式模式中有未转义的字符。 .有一个特殊的正则表达式用法,所以为了表明你只是指一个实际的句号,他们必须在它们之前有一个反斜杠。试试这个:

(https://clips\.twitch\.tv/)(?:(?!http).)*?(video_thumbnail)

另请注意,^和$已消失;如果你包括那些,它只会匹配整个字符串匹配。

相关问题