【问题标题】:Remove specific words from a string (case insensitive)从字符串中删除特定单词(不区分大小写)
【发布时间】:2012-08-03 00:24:09
【问题描述】:

我得到的工作内容包含许多我想从内容中“删除/替换”的单词。示例:

postcodes,Thank you , Click here 

问题

我有一个要从内容中删除的单词列表,但我不确定这些单词在内容中的显示方式(大写/小写)...

那么,我该如何替换它们呢?

示例 - 我想替换:

associate degree in electronics or applicable equivalent

但在内容上可以:

associate Degree in electronics or applicable equivalent
Associate DEGREE in electronics or applicable equivalent
ASSOCIATE DEGREE IN ELECTRONICS or applicable equivalent

如何替换它们?

【问题讨论】:

    标签: c# .net regex winforms replace


    【解决方案1】:

    试试这个:

    (?i)(associate DEGREE in ELECtronics)
    

    【讨论】:

    • 有必要放|在单词之间?如果我有这样的文字怎么办:你好,早上好朋友!!!
    • @confusedMind, | 是逻辑或。换句话说,这个正则表达式匹配 associatedegree 或 ...
    • 或者,假设我在内容方面拥有科学副学士学位,它是否也会因为我不想要它而删除副学士学位?
    • @confusedMind,它将删除正则表达式中指定的任何单词。在这种情况下:associatedegreein
    • 非常感谢您的帮助!真的很感激。
    【解决方案2】:

    如果您想使用正则表达式,一种可能的解决方案是:

    Regex.Replace(input, @"(?i)(associate\s+degree\s+in\s+electronics\s+or\s+applicable\s+equivalent)", String.Empty);
    

    您可以使用相同的模式但创建一个 Regex 对象,因此您可以提供 RegexOptions 如下:

    Regex r = new Regex(@"(?i)(associate\s+degree\s+in\s+electronics\s+or\s+applicable\s+equivalent)", RegexOptions.Compiled);
    

    以后您可以将其用作:

    r.Replace(input, String.Empty);
    

    注意:使用具体的 Regex 对象可以让您利用更灵活的替换策略,例如 MatchEvaluator、替换次数作为计数等...

    【讨论】:

    • 感谢您发布答案,但我几分钟前才得到帮助 :)。
    猜你喜欢
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多