【问题标题】:Regex: Find Word ignoring innertext in Anchor tag正则表达式:在锚标记中查找忽略内部文本的单词
【发布时间】:2012-02-13 22:07:06
【问题描述】:

使用 .NET。

要搜索的示例字符串:

For more information on foreclosures visit <a href="http://www.us.gov/foreclosures.aspx">forclosures</a>

需要正则表达式来查找(并随后替换)这个字符串中的单词 foreclosures...但只有锚标记之外的实例。所以在这个例子中,只有单词“foreclosures”的第一个实例应该匹配。锚标记内的任何内容都应完全忽略。

我目前的正则表达式(还没有正确排除内部文本)是:

\bforeclosures(?!([^<]+)?>)

更新:在已经提供第一个响应之后... 我使用的是 VB.NET,但我也精通 C#。

【问题讨论】:

    标签: .net regex regex-negation


    【解决方案1】:

    有时最好多一步做事而不是一步做事。与其花几个小时想出完美的正则表达式来统治它们,不如先删除所有 html 标签,只需调用Regex.Replace

    // Remove html tags
    var htmlTagPattern = new Regex(@"<([A-Z][A-Z0-9]*)\b[^>]*>", RegexOptions.IgnoreCase);
    var noTags = htmlTagPattern.Replace(input, string.Empty);
    
    // Find those words
    var foreclosuresPattern = new Regex(@"foreclosures", RegexOptions.IgnoreCase);
    var matches = foreclosuresPattern.Matches(noTags);
    

    编辑:原来的帖子只提到了finding字。 替换字词的需要增加了一点复杂性。

    // Try and find all cases
    private string findAndTag(string input) {
        var pattern = new Regex(@"(\x3c[A-Z][A-Z0-9]*[^\x3e]*)?(foreclosures)([^\x3c\x3e]*>)?", RegexOptions.IgnoreCase);
        return pattern.Replace(matches, replacer);
    }
    
    private string replacer(Match match) {
        if (match.Groups[1].Success) {
            // Found the word foreclosures inside a tag, for
            // example <a href="foreclosures">...
            // Just return the original match - don't replace
            return match.Value;
        }
        else {
            // Found the word outside of tags
            // Tag it and return it
            return "<span>" + match.Value + "</span>";
        }
    }
    

    【讨论】:

    • 问题是我必须找到并用同一个词的标记版本替换这个词,但只能在锚标记之外。
    • 从语法上讲,您提供的正则表达式在 RegExBuddy 中给了我一些问题......在)?部分,你能确认一下正则表达式吗?
    • 它在正则表达式中运行良好:regexr.com?2vp50 - 在我的测试 ConsoleApp 中运行良好。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多