Reputation: 2052
I am trying to regex a string in csharp. I am expecting to pass a string with the following format:
<%=Application(\"DisplayName\")%>
and get back:
DisplayName
I am using the regex class to accomplish this:
var text = "<%=Application(\"DisplayName\")%>";
Regex regex = new Regex(@"(<\%=Application[\>\(\)][\\][""](.*?)[\\][""][\>\(\)k]%\>)");
var v = regex.Match(text);
var s = v.Groups[1].ToString();
I am expecting s
to contain the output string, but it is coming back as ""
. I tried building the regex string step by step, but I can't get the \
or "
to process correctly. Any help would be greatly appreciated. Thanks!
Upvotes: 0
Views: 56
Reputation: 2153
Your pattern is very close. Since the backslashes are not actually a part of the string, rather only in the string to escape the double quotes, they need to be left out of the regex pattern. Notice I removed the [\\]
from before both of the double quotes [""]
.
Now, you expect DisplayName
in Group[1]
. Since Regex sticks the entire match in Group[0]
, that made your outer capture group (whole pattern in parenthesis) the first actual capture group (Making DisplayName
actually Group[2]
). For best practice, I changed the outer capture group to be a non-capture group by adding ?:
to the open parenthesis. This ignores this full group and makes DisplayName
Group[1]
. Hope this helps.
Full test code:
var text = "<%=Application(\"DisplayName\")%>";
Regex regex = new Regex(@"(?:<\%=Application[\>\(\)][""](.*?)[""][\>\(\)k]%\>)");
var v = regex.Match(text);
var s = v.Groups[1].ToString();
Upvotes: 1
Reputation: 1450
var text = "<%=Application(\"DisplayName\")%>";
Regex regex = new Regex(@"(<%=Application[>()][""](.*?)[""][>()k]%>)");
var v = regex.Match(text);
var s = v.Groups[1].ToString();
Upvotes: 1