-1

I am trying to run this regex in c#:

\{\"secret\":\"(.*?)\",\"encrypted":\"(.*?)\"\}

This is what I am trying to match:

{"secret":"xxx","encrypted":"xxxgggxxx"}

Because it needs to be further escaped in c# I tried following:

 var test = Regex.Match(html, "\\{\\\"secret\\\":\\\"(.*?)\\\",\\\"encrypted\\\":\\\"(.*?)\\\"\\}");

But it gives me 0 matches. What is the correct way to escape the quotes and curly braces? I have tested the regex in an online tester it should work.

Thomas Segato
  • 4,567
  • 11
  • 55
  • 104
  • If you got to escape a lot of characters in one string, you can just surpess the need to escape with the @: https://www.codeproject.com/Articles/371232/Escaping-in-Csharp-characters-strings-string-forma Think of it like the "Capslock for escaping" – Christopher Aug 06 '19 at 11:46
  • 3
    Do not use regex. Use JSON.NET. – Wiktor Stribiżew Aug 06 '19 at 11:47
  • I started that road. But same applies var pattern = @"\\{\\"secret\\":\\"(.*?)\\",\\"encrypted":\\"(.*?)\\"\\}" and var pattern = @"\{\"secret\":\"(.*?)\",\"encrypted":\"(.*?)\"\}" – Thomas Segato Aug 06 '19 at 11:49
  • @ThomasSegato You don't need to escape the curly brackets or double quotes for the regular expression. But when using a verbatim string you only have to escape double quotes with another double quote like `@"I don't need to escape a \, but this is how a "" is escaped"` – juharr Aug 06 '19 at 11:51
  • And your regex works. [This](https://regex101.com/r/4GIHvc/1) is the result when using the `Regex.Match(html, "\\{\\\"secret\\\":\\\"(.*?)\\\",\\\"encrypted\\\":\\\"(.*?)\\\"\\}")`. – Wiktor Stribiżew Aug 06 '19 at 12:05
  • @WiktorStribiżew it is a html document so json.net will not work. – Thomas Segato Aug 06 '19 at 14:47

1 Answers1

0

Try this

string strRegex = @"{""secret"":""(.*?)"",""encrypted"":""(.*?)""}";    
string strTargetString = @"{""secret"":""xxx"",""encrypted"":""xxxgggxxx""}";
var test = Regex.Match(strTargetString, strRegex ):
Antoine V
  • 6,998
  • 2
  • 11
  • 34