【问题标题】:C# String Get Between in a HTML Code [duplicate]C#字符串在HTML代码之间获取[重复]
【发布时间】:2014-04-18 12:28:47
【问题描述】:

我有一个包含以下内容的字符串变量:

(<b><a href="#post9736461" title="Show">Permalink</a></b>)

我怎样才能在一个额外的变量中获得9736461?字符串总是一样的,只是数字变了。

编辑:

我试过了:

Tag = Regex.Replace(Tag, @"(<b><a href=\"#post");
Tag = Regex.Replace(Tag, @"" title=\"Show\">Permalink</a></b>)");

【问题讨论】:

  • 使用适当的库进行 Html 解析。以HtmlAgilityPack 为例
  • @Steve 对于这个 sn-p,您不需要 HTML 解析库。它在语法上是纯 XML,因此可以使用 XML 和 XPath 处理。
  • 如果这个小字符串除了数字部分是不变的,我认为使用解析库没有任何意义。
  • @martin_costello 查看我的编辑
  • 所有你需要做的就是抓住数字? stackoverflow.com/questions/4734116/…

标签: c# regex string replace


【解决方案1】:

下面的代码就可以了:

string input = "(<b><a href=\"#post9736461\" title=\"Show\">Permalink</a></b>)";
string value = Regex.Match(input, @"(?<=#post)\d+").Value;

【讨论】:

    【解决方案2】:
    (?<=#post)(\d+)
    

    将为您提供\1中的号码

    【讨论】:

    • 如果您使用零宽度后向引用,则无需反向引用。我也怀疑这对于对正则表达式了解不多的人来说非常清楚。
    【解决方案3】:
    resultString = Regex.Replace(subjectString, @"(#post\d+)""", "$1");
    
    Match the regular expression below and capture its match into backreference number 1 «(#post\d+)»
       Match the characters “#post” literally «#post»
       Match a single digit 0..9 «\d+»
          Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
    Match the character “"” literally «"»
    

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 2015-10-09
      • 1970-01-01
      • 2012-07-15
      • 2022-12-13
      • 1970-01-01
      • 2019-10-05
      • 2015-10-16
      • 1970-01-01
      相关资源
      最近更新 更多