【问题标题】:regex replace matches with function and delete other matches正则表达式用函数替换匹配并删除其他匹配
【发布时间】:2014-01-28 20:22:10
【问题描述】:

我有一个类似下面的字符串,我想用函数的输出替换 FieldNN 实例。

到目前为止,我已经能够用函数的输出替换 NN 实例。但我不确定如何使用相同的正则表达式删除静态“字段”部分。

输入字符串:

(Field30="2010002257") and Field1="yuan" not Field28="AAA"

需要的输出:

(IncidentId="2010002257") and Author="yuan" not Recipient="AAA"

这是我目前的代码:

public string translateSearchTerm(string searchTerm) {
    string result = "";

    result = Regex.Replace(searchTerm.ToLower(), @"(?<=field).*?(?=\=)", delegate(Match Match) {
        string fieldId = Match.ToString();
        return String.Format("_{0}", getFieldName(Convert.ToInt64(fieldId)));
    });

    log.Info(String.Format("result={0}", result));

    return result;
}

给出:

(field_IncidentId="2010002257") and field_Author="yuan" not field_Recipient="aaa"

我想解决的问题是:

  1. 从输出中删除静态“字段”前缀。
  2. 使“FieldNN”部分的正则表达式不区分大小写,而不是小写引用的文本部分。
  3. 使正则表达式更加健壮,以便引用的字符串部分使用双引号或单引号。
  4. 使正则表达式更加健壮,以便忽略空格:FieldNN = "AAA" vs. FieldNN="AAA"

我真的只需要解决第一个问题,其他三个将是一个奖励,但一旦我发现了正确的空格和引号模式,我可能会解决这些问题。

更新

我认为下面的模式解决了问题 2. 和 4.

result = Regex.Replace(searchTerm, @"(?<=\b(?i:field)).*?(?=\s*\=)", delegate(Match Match) 

【问题讨论】:

  • 我不完全理解你的第二和第三期 - 2)现在正则表达式不区分大小写。 3)您不更改值部分,那么为什么需要将其包含在正则表达式中?
  • @Yevgeniy.Chernobrivets 2) 是的,它不区分大小写,但它也将引用的字符串小写。 3)我不改变值部分,但我担心模式会匹配值部分中的 FieldNN(如果表达式太贪婪?)

标签: c# regex matchevaluator


【解决方案1】:

要解决第一个问题,请使用组而不是积极的后视:

public string translateSearchTerm(string searchTerm) {
    string result = "";

    result = Regex.Replace(searchTerm.ToLower(), @"field(.*?)(?=\=)", delegate(Match Match) {
        string fieldId = Match.Groups[1].Value;
        return getFieldName(Convert.ToInt64(fieldId));
    });

    log.Info(String.Format("result={0}", result));

    return result;
}

在这种情况下,“字段”前缀将包含在每个匹配项中并被替换。

【讨论】:

  • 谢谢@Yevgeniy.Chernobrivets :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 2022-12-01
  • 2016-07-04
  • 2013-12-06
相关资源
最近更新 更多