1

I have a huge json string. I want to replace all "_abc" reference of property name to "Abc". How to do it with Regex in C#?

With normal .net replace, I can do following to remove the "_" instance but not sure how to convert first letter to Uppercase then.

text = jsonString.Replace("\"_", "\"");

Thanks, Jay

Jay Nanavaty
  • 1,089
  • 1
  • 15
  • 29
  • Wouldn't a safer bet be to iterate your JSON string using a library and then do a replace on the keys/values of interest? – Tim Biegeleisen Jul 15 '18 at 10:09
  • I tried that but it turned out to be very slow. I used json.net and contract type resolver approach to do so. – Jay Nanavaty Jul 15 '18 at 10:11
  • 1
    What you want to try is `text = Regex.Replace(jsonString, @"_(\p{Ll})", m => m.Groups[1].Value.ToUpper());`, but you should only run a regex against plain text, JSON is not plain text. – Wiktor Stribiżew Jul 15 '18 at 10:12
  • there is an answer in this thread which you may find useful https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive – Y.S Jul 15 '18 at 10:17
  • 1
    regex will be 10 to 100 times slower then just parsing the string your self in an fixed array using unsafe and upper-casing the next char after an underscore, just saying... oh wait, that's not what you wanted – TheGeneral Jul 15 '18 at 10:17
  • So you just want to remove anything that starts with _ and convert the first char uppercase? – TheGeneral Jul 15 '18 at 10:48
  • yes. That is what I want. – Jay Nanavaty Jul 15 '18 at 10:51

1 Answers1

4

Because you wanted speed, this may or may not interest you

unsafe public static string Convert(string input)
{
   fixed (char* pInput = input)
   {
      char* p1, p2, len = pInput + input.Length;
      for (p1 = p2 = pInput + 1; p2 < len; p1++, p2++)
         *p1 = *(p2 - 1) == '"' && *p2 == '_' ? char.ToUpper(*++p2) : *p2;
      return input.Substring(0, (int)(p1 - pInput));
   }
}

It simply replaces, "_<char> to "<Upper case char>

On my pc it can do 445 Mb 1.8 seconds

Sample Input

{
   "menu":{
      "id":"_file",
      "value":"_file",
      "popup":{
         "menuitem":[
            {
               "value":"_new",
               "onclick":"_createNewDoc()"
            },
            {
               "value":"_open",
               "onclick":"_openDoc()"
            },
            {
               "value":"_close",
               "onclick":"_closeDoc()"
            }
         ]
      }
   }
}

Output

{
   "menu":{
      "id":"File",
      "value":"File",
      "popup":{
         "menuitem":[
            {
               "value":"New",
               "onclick":"CreateNewDoc()"
            },
            {
               "value":"Open",
               "onclick":"OpenDoc()"
            },
            {
               "value":"Close",
               "onclick":"CloseDoc()"
            }
         ]
      }
   }
}

Additional resources

TheGeneral
  • 79,002
  • 9
  • 103
  • 141