【问题标题】:How to ignore a specific string while searching for a pattern in Regex?在正则表达式中搜索模式时如何忽略特定字符串?
【发布时间】:2014-10-21 00:43:50
【问题描述】:

我有一个查询,我用方括号括起来的关键字替换模式中指定的所有关键字。

如果我的查询已经有Select [key] from table1,我应该忽略并避免替换它:

var pattern = @"(?i)Key|IN|ON|VIEW";
var subject = "Select key from table1";
var result = Regex.Replace(subject, pattern, @"[$0]");

如何做到这一点?

【问题讨论】:

    标签: c# regex regex-negation


    【解决方案1】:

    您可以使用前瞻来忽略关键字周围的匹配 [ 和 ]:

    var pattern = @"(?i)(?<!\[)(?:Key|IN|ON|VIEW)(?!\])";
    

    RegEx Demo

    【讨论】:

    • 感谢 Anubhav ..它成功了。但你能告诉我 (?
    • 不客气。我提供的链接在 RHS 上解释了这个正则表达式。另请查看这篇关于正则表达式环视的非常有用的文章:regular-expressions.info/lookaround.html
    猜你喜欢
    • 2014-03-04
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多