仅当存在匹配项时才返回true,但不是第一个匹配项

发声的

我想我已经在标题中写了我想做的事情,所以到现在为止:

  1. 我有一个带有url链接的.txt文件,其源代码将通过正则表达式进行解析。
  2. 每个链接的源代码都是通过以下方式抓取的:

    public static string getSourceCode(string url)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        StreamReader sr = new StreamReader(resp.GetResponseStream());
        string sourceCode = sr.ReadToEnd();
        sr.Close();
        resp.Close();
        return sourceCode;
    }
    

每个源代码都包含以下文本:

..code..
..code..
    <p class="content">

                                exampleexampleexample

                                        </p>
..code..
..code..
    <p class="content">

                                example

                                        </p>
..code..
..code..

元素的content元素更多

  1. 我得到的content内容是这样的:

Regex k = new Regex(@"<p class=""question-content"">[\r\n\s]*(\S.*)"); var g = k.Matches(sourceCode);

现在,我可以轻松提取每个匹配项:

g[1].ToString() <-- first match
g[2].ToString() <-- second match
g[3].ToString() <-- thirdmatch

等等。

但是我想做的是在以下位置提取这些链接:第一个匹配项不包含XYZ,但XYZ至少存在其他匹配项。

例如:

第一个链接的源代码包含XYZ第一个和第三个匹配<-错误

第二个链接的源代码XYZ包含第一个匹配<-错误

第三个链接的源代码XYZ包含第三个匹配项<-成功!

解决方案

我从这里得到了每场比赛的成功:

MatchCollection b1 = Regex.Matches(sourceCode, @"<p class=""content"">[\r\n\s]*(\S.*)");

我接下来要做的是通过以下方法检查第一个匹配项是否不包含“ example”:

if (!b1[0].ToString().Contains("example"))

并检查此功能的结果:

bool checkAnother(int amount, MatchCollection m)
{     
    for (int i=1; i<=amount-1; i++)
    {
        if (m[i].ToString().Contains("example"))
            return true;
    }
    return false;
}

这就是代码:

            MatchCollection b1 = Regex.Matches(sourceCode, @"<p class=""content"">[\r\n\s]*(\S.*)");

            if ((!b1[0].ToString().Contains("example")) && (checkAnother(b1.Count, b1)))
            {dataGridView1.Rows[i].Cells[2].Value = "GOOD";                   
            }
晚安书呆子骄傲

您尝试执行的操作不适用于正则表达式。

多行匹配,捕获组和环视可能是可能的,但是IMO花费大量精力到无法维护的解决方案中是不值得的。

尝试在后处理步骤中验证找到的匹配项。假设您像这样抓住比赛:

var g = k.Matches(sourceCode);

...您可以轻松实现以下目标:

var isFirstOk = !g[0].Value.Contains("XYZ");
var areAllOk = isFirstOk && g.Cast<Match>().Skip(1).Any(m => m.Value.Contains("XYZ"));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章