0

Goal:
Make the regex code to be working in C# code

Problem:
What syntax do I miss in order to make the regex code to be working in C#. The regex code from https://regexr.com/578ul works but not at onelinegdb (https://www.onlinegdb.com/HycbSKxAL)

I have a symbol '"' that is part of the regex code but csharp consider it as a part of c# and not as a symbol.


Regex

,["0x465a27d8333756e1:0x66460f22856aea3b","broadway 22, 123 45 ny",null,[null,null,55.0359401,13.9717872]
,0,1]

C# code

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"","broad.*]";
        string input = @",["0x465a27d8333756e1:0x66460f22856aea3b","broadway 22, 123 45 ny",null,[null,null,55.0359401,13.9717872]
,0,1]"


        foreach (Match m in Regex.Matches(input, pattern))
        {
            Console.WriteLine(m.Value);
        }
    }
}

Regex:
https://regexr.com/578ul

Onlinegdb with C# code:
https://www.onlinegdb.com/HycbSKxAL

Thank you!

HelloWorld1
  • 13,688
  • 28
  • 82
  • 145
  • 1
    Just escape it like `"\""` . Also I would be carefull with `]` character, as it's regex character used to denote character classes, so it should be escaped as well like `\]` – Michał Turczyn Jun 24 '20 at 07:57
  • @MichałTurczyn it [seems](https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-escapes-in-regular-expressions#character-escapes-in-net) that only `[` needs to be escaped for single usage (unless `]` is used in `[]`). – Guru Stron Jun 24 '20 at 08:11
  • 1
    Does this answer your question? [Escape double quotes in string](https://stackoverflow.com/questions/14480724/escape-double-quotes-in-string) – Charleh Jun 24 '20 at 08:16

1 Answers1

0

To escape " character in verbatim string you can use another " character, so every occurrence of "" inside it will be translated to single " character:

var str = @""""; // string consisting of one "

So your pattern will look like this:

string pattern = @""",""broad.*]";

And input:

string input = @",[""0x465a27d8333756e1:0x66460f22856aea3b"",""broadway 22, 123 45 ny"",null,[null,null,55.0359401,13.9717872]
,0,1]";

But in this particular case it seems that it will be easier to use simple string with \ escape:

string pattern = "\",\"broad.*]";
Guru Stron
  • 102,774
  • 10
  • 95
  • 132