0

I am trying to fetch a particular field's value from a string using the below code.

Example Code:

string contents = "2018-07-31 \"streetAddress1\":{\"1 Harbour Street\"},\"streetAddress2\":{\"2 Lords Road\"}";

string streetAddress1 = ValueFinder(contents, "\"streetAddress1\"", "\"streetAddress2\"");

...

public string ValueFinder(string contents, string startText, string endText)
{
    int indexPos1 = contents.IndexOf(startText);
    int indexPos2 = contents.IndexOf(endText);

    if(indexPos1 != -1 && indexPos2 != -1)
    {
        string finalValue = contents.Substring(indexPos1 + (startText.Length + 3), indexPos2 - indexPos1 - (startText.Length + 3));
        return finalValue.Split(':')[1];
    }
    return "";
}

In the above code, I am able to get whats between the two fields. However, is there a simpler way to get the values between flower braces {} if I give a field's name.

Example, if field's name is "streetAddress1" then it should output its values as "1 Harbour Street" instead of my current logic where I have specified two fields in order to fetch the first field's value.

Thank you.

Alphonsa
  • 39
  • 5
  • Looks a *bit* like JSON to me (with a date at the start). Have you considered using a JSON parser rather than trying to use a Regex? For example... https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – Richardissimo Aug 02 '18 at 12:53
  • Is your string json format? if so possible duplicate https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – Adam Aug 02 '18 at 12:56
  • Just because it has `:` and `{` (colon and braces) doesn't mean it's JSON. – Danon Aug 02 '18 at 13:27
  • Please think about what happens in your code if the `endText` occurs before the `startText` and so `indexPos1 > indexPos2`. – AdrianHHH Aug 02 '18 at 13:54
  • This is not json format. I am reading from logs from our application server. It doesn't have to be in json format though the field I am fetching looks like json. Would be helpful if you can share an idea using regex to fetch between {}.. – Alphonsa Aug 03 '18 at 02:52

0 Answers0