【问题标题】:Regex - lookahead / LookBehind assertion正则表达式 - 前瞻 / LookBehind 断言
【发布时间】:2014-08-02 17:49:39
【问题描述】:

我想测试以下文本的正则表达式

  <div class="creditItem"><a href="/maren_addy/beauty-ful/"></a></div>      
<a href="abc.aspx">test</a>
<div class="creditItem"><a href="/maren_addy/beauty-ful2/"></a> </div>  

正则表达式

(?.?href=").?(?=")

预期输出

/maren_addy/beauty-ful/
/maren_addy/beauty-ful2/

但是得到这个输出

/maren_addy/beauty-ful/
abc.aspx
/maren_addy/beauty-ful2/

有人可以解释并纠正正则表达式

谢谢

【问题讨论】:

  • 如果这意味着用于 HTML 解析,您最好寻找一个专用库而不是 Regex。
  • 不要使用正则表达式进行 HTML 解析。这只是冰山一角!

标签: c# asp.net regex


【解决方案1】:

你可以试试下面的正则表达式,

(?<=class="creditItem"><a href=").*?(?=")

DEMO

C# 代码是,

String input = @"  <div class=""creditItem""><a href=""/maren_addy/beauty-ful/""></a></div>      
<a href=""abc.aspx"">test</a>
<div class=""creditItem""><a href=""/maren_addy/beauty-ful2/""></a> </div>  ";
Regex rgx = new Regex(@"(?<=class=""creditItem""><a href="").*?(?="")");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[0].Value);

IDEONE

【讨论】:

  • 如果我将输入字符串更改为这样
    test
    ..它不会工作请检查
  • (?&lt;=class="creditItem"&gt; ?&lt;a href=").*?(?=")(?&lt;=class="creditItem"&gt;\s*&lt;a href=").*?(?=") 将匹配两者。
  • 感谢它运行良好.. 你能解释一下为什么这不起作用吗 (?.*?
【解决方案2】:

从索引 1 获取匹配组

(?<=class="creditItem"><a href=")([^"]*)

DEMO

阅读Want to Be Lazy? Think Twice.

【讨论】:

    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2013-08-19
    相关资源
    最近更新 更多