-1

c# has Interpolated strings. This means that this string:

"{Variable} Text \{NotVariable\}"

corresponds to:

Variable + "Text {NotVariable}"

I need to check, that the string is allowed AND spil in into a list of the inputs, eg. Variable and "Text {NotVaraible}".

A guy posted a similar question, but I can't modify the answer to suit my need. Link to similar problem

Does anyone have a propper solution?

Community
  • 1
  • 1
user3265569
  • 175
  • 2
  • 11
  • You mean you have to process some literal `"{Variable} \"Text \{NotVariable\}\""`? – Wiktor Stribiżew Apr 28 '16 at 10:29
  • I need to convert the string "{Variable} Text \{NotVariable\}" into two different strings. – user3265569 Apr 28 '16 at 10:40
  • Well, there is something unclear: escaping the `{` and `}` in interpolated strings means doubling them. So, the example should read `$"{Variable} \"Text\" {{NotVariable}}"`, and you need to turn that into `Variable + "\"Text\" {{NotVariable}}"`? – Wiktor Stribiżew Apr 28 '16 at 10:54

1 Answers1

1

You might try the following regex:

(?s)(?<bndr>\$"|(?!^)\G)     # Get the start of the interpolated string literal or the end of previous match
(?:
 (?<var>{[^}]*})             # Match a variable {non-braces-inside}
 |                           # OR...
 (?<literal>(?:\\.|{{|}}|[^"\\{}])*) # Escaped entities or everything else
)

See this C# demo results:

var Variable = "";
var input_text = "$\"text1 {Variable} \\\"Text\\\" {{NotVariable}}\"";
var pat = @"(?s)(?<bndr>\$""|(?!^)\G)(?:(?<var>{[^}]*})|(?<literal>(?:\\.|{{|}}|[^""\\{}])*))";
var matches = Regex.Matches(input_text, pat)
     .Cast<Match>()
     .Select(p => p.Groups["var"].Success ? p.Groups["var"].Value.Trim(' ', '{', '}') : "\"" + p.Groups["literal"].Value.Replace("{{", "{").Replace("}}", "}") + "\"")
     .ToList();
matches.RemoveAll(p => p == "\"\"");
Console.WriteLine(string.Join(" + ", matches));                             //"text1 " + Variable + " \"Text\" {NotVariable}"
var result_string = "text1 " + Variable + " \"Text\" {NotVariable}" + "";   //text1  "Text" {NotVariable}
var check_string = $"text1 {Variable} \"Text\" {{NotVariable}}";            //text1  "Text" {NotVariable}

The result_string that is built from the output of joined matches and check_string (actual interpolated string) are equal.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563