0

I have a string like the one below and I want to replace the FieldNN instances with the ouput from a function.

So far I have been able to replace the NN instances with the output from the function. But I am not sure how I can delete the static "field" portion with the same regex.

input string:

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

required output:

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

This is the code I have so far:

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;
}

which gives:

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

The issues I would like to resolve are:

  1. Remove the static "field" prefixes from the output.
  2. Make the regex case-insenitive on the "FieldNN" parts and not lowercase the quoted text portions.
  3. Make the regex more robust so that the quoted string parts an use either double or single quotes.
  4. Make the regex more robust so that spaces are ignored: FieldNN = "AAA" vs. FieldNN="AAA"

I really only need to address the first issue, the other three would be a bonus but I could probably fix those once I have discovered the right patterns for whitespace and quotes.

Update

I think the pattern below solves issues 2. and 4.

result = Regex.Replace(searchTerm, @"(?<=\b(?i:field)).*?(?=\s*\=)", delegate(Match Match) 
hairyone
  • 439
  • 1
  • 5
  • 16
  • I do not fully understand you second and third issue - 2) Right now regex is case insensitive. 3) You do not change value part so why you need to include it in regex? – Yevgeniy.Chernobrivets Jan 28 '14 at 20:50
  • @Yevgeniy.Chernobrivets 2) Yes it is case insensitive but it also lowercases the quoted strings as well. 3) I don't change value part but I was worried that the patter would match a FieldNN that was in the value part (if the expression is too greedy?) – hairyone Jan 28 '14 at 21:14

1 Answers1

0

To fix first issue use groups instead of positive lookbehind:

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;
}

In this case "field" prefix will be included in each match and will be replaced.

Yevgeniy.Chernobrivets
  • 3,194
  • 2
  • 12
  • 14