【问题标题】:What am I doing wrong with my Regex?我的正则表达式做错了什么?
【发布时间】:2010-12-17 08:22:24
【问题描述】:

我不确定我做错了什么。我正在尝试使用 asp.net regex.replace,但它一直在替换错误的项目。

我有 2 个替换。第一个做我想要的,它取代了我想要的。几乎是镜像的下一个替换不会替换我想要的。

这是我的示例代码

<%@ Page Title="Tour" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <title>Website Portfolio Section - VisionWebCS</title>
    <meta name="description" content="A" />
    <meta name="keywords" content="B" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <!-- **START** -->

我正在寻找替换这两个元标记。

<meta name=\"description\" content=\"A\" />
<meta name=\"keywords\" content=\"B\" />

在我的代码中,我首先将关键字元标记替换为

<meta name=\"keywords\" content=\"C\" />

这行得通,所以我的下一个任务是用这个替换描述元标记

<meta name=\"description\" content=\"D\" />

这不起作用,而是替换“关键字”元标记,然后替换“描述”标记。

这是我的测试程序,大家可以试试。只需在 C# 控制台应用程序中通过它。

  private const string META_DESCRIPTION_REGEX = "<\\s* meta \\s* name=\"description\" \\s* content=\"(?<Description>.*)\" \\s* />";
        private const string META_KEYWORDS_REGEX = "<\\s* meta \\s* name=\"keywords\" \\s* content=\"(?<Keywords>.*)\" \\s* />";
        private static RegexOptions regexOptions = RegexOptions.IgnoreCase
                                   | RegexOptions.Multiline
                                   | RegexOptions.CultureInvariant
                                   | RegexOptions.IgnorePatternWhitespace
                                   | RegexOptions.Compiled;

        static void Main(string[] args)
        {

            string text = "<%@ Page Title=\"Tour\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" Inherits=\"System.Web.Mvc.ViewPage\" %><asp:Content ID=\"Content1\" ContentPlaceHolderID=\"HeadContent\" runat=\"server\">    <title>Website Portfolio Section - VisionWebCS</title>    <meta name=\"description\" content=\"A\" />    <meta name=\"keywords\" content=\"B\" /></asp:Content><asp:Content ID=\"Content2\" ContentPlaceHolderID=\"MainContent\" runat=\"server\"><!-- **START** -->";
            Regex regex = new Regex(META_KEYWORDS_REGEX, regexOptions);
            string newKeywords = String.Format("<meta name=\"keywords\" content=\"{0}\" />", "C");
            string output = regex.Replace(text, newKeywords);

            Regex regex2 = new Regex(META_DESCRIPTION_REGEX, regexOptions);
            string newDescription = String.Format("<meta name=\"description\" content=\"{0}\" />", "D");
            string newOutput = regex2.Replace(output, newDescription);
            Console.WriteLine(newOutput);
        }

这得到了我的最终输出

<%@ Page Title="Tour" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHold erID="HeadContent" runat="server">
    <title>Website Portfolio Section - VisionW
        ebCS</title>
    <meta name="description" content="D" />
</asp:Content>
<asp:Conten t ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <!-- **START**
    -->

谢谢

【问题讨论】:

    标签: c# .net regex .net-3.5


    【解决方案1】:

    你做错了什么?你是parsing HTML with a regex

    .NET 推荐库:HTML Agility Pack

    【讨论】:

    • 那么 - 那么你会怎么做呢?
    • @Will: +1 但你应该提供一个链接/代码片段如何用适当的解析器解析它
    • 光是图片就够搞笑了,点击一下
    • @marc_S 我的想法完全正确。只是快速浏览一下文章似乎并没有显示要使用什么。它还说在某些情况下你可以。我能够多次解析 html 而没有问题,它比我现在所做的复杂 100 倍。
    【解决方案2】:

    要在没有无用的人生课程的情况下回答您的问题,您会因为贪婪的量词而遇到麻烦。尝试通过添加问号让他们变得懒惰:

    <meta\\s+?name=\"description\"\\s+?content=\"(?<Description>.*?)\"\\s*?/>
    

    当然,此正则表达式不适用于世界上的所有页面,但如果您只需要为自己的模板制作一些快速替换脚本,正则表达式是最快和最简单的解决方案,也是可行的方法。

    【讨论】:

    • 嗯,可以,但我不明白。我想即使我使用了一个贪婪的量词,它也会继续运行,直到它看到“/>”并停止。那么为什么它会走得更远呢?就像即使在检查捕获的表达式数量时,它也总是返回一个。
    【解决方案3】:

    我同意 @serg555 的回答 - 问题在于贪婪的量词 - 让他们懒惰地使用 '?'应该能解决问题

    <meta\\s*name=\"description\"\\s*content=\"(?<Description>.*?)\"\\s*/>
    

    【讨论】:

      【解决方案4】:

      学习、喜爱和使用 DOM。它是 W3C(HTML 标准机构)认可的解析 XML(HTML 是 XML 的子集)文档的方法。除非您有足够的理由相信您输入的 HTML 是非常错误的,否则这通常是最好的开始方法。

      Learn here

      强烈建议您结帐 Walkthrough: Accessing the DHTML DOM from C#

      您可能还想尝试 jQuery,因为它使搜索 DOM 变得非常容易。 Like so.

      【讨论】:

        【解决方案5】:

        我需要 C# 代码中的 URL 描述并使用 this site 检查我的正则表达式代码。

        这是我的最终作品:

              WebClient x = new WebClient { Encoding = Encoding.UTF8 };
                    string source = x.DownloadString(url);
        
                    string description = Regex.Match(source, "<meta[^>]*name=[\"|\']description[\"|\'][^>]*content=[\"]([^\"]*)[\"][^>]*>", RegexOptions.IgnoreCase).Groups[1].Value;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-07-27
          • 1970-01-01
          • 2012-11-19
          • 2021-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多