I am writing a Regex to extract string enclosed within different type of double quotes ("
, “
, ”
).
So far I have written below code, it works as expected but the regex is quite big and I think it can be improved.
//mergeField = {{field(“dd/MMM/yyyy")}}
var startIndex = mergeField.IndexOf('(');
var endIndex = mergeField.IndexOf(')');
string format = mergeField.Substring(startIndex: startIndex + 1, length: endIndex - startIndex - 1);
string formatSpecifierPattern = string.Format(@"{0}|{1}|{2}|{3}|{4}|{5}", @"(\“.*?\”)|(\”.*?\”)", "\\\"(.*?)\\\"", "“(.*?)\\\"", "\\\"(.*?)“", "”(.*?)\\\"", "\\\"(.*?)”");
MatchCollection matches = Regex.Matches(format, formatSpecifierPattern);
In above code, mergeField is passed as a parameter and it can have a different combination of quotes. Is there any way I can simplify my Regex and handle all combinations ("
, “
, ”
)
Input - Expected Output
{{field(“dd/MMM/yyyy")}} -> “dd/MMM/yyyy"
{{field("dd/MMM/yyyy“)}} -> "dd/MMM/yyyy“
{{field("dd/MMM/yyyy")}} -> "dd/MMM/yyyy"
{{field(“dd/MMM/yyyy“)}} -> “dd/MMM/yyyy“
{{field(“dd/MMM/yyyy“)}} -> “dd/MMM/yyyy“
{{field(”dd/MMM/yyyy")}} -> ”dd/MMM/yyyy"
{{field("dd/MMM/yyyy”)}} -> "dd/MMM/yyyy”
{{field(”dd/MMM/yyyy”)}} -> ”dd/MMM/yyyy”