Jorje Redemption Jorje Redemption - 3 months ago 9
ASP.NET (C#) Question

How do i use Regex in C# to extract @ViewData variable values from a cshtml page?

I have the following cshtml page:

<div class="container ptb-60">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading">@ViewData["PageTitle"]</h2>
<p class="lead">@ViewData["Excerpt"]</p>
<p>
<a class="btn btn-primary btn-lg" href="@ViewData["Template.HeaderButton.Url"]" role="button">@ViewData["Template.HeaderButton.Text"]</a>
</p>
</div>
<div class="col-md-5">
<img class="featurette-image img-responsive center-block" src="@ViewData["Template.HeaderButton.Image"]" alt="@ViewData["Template.HeaderButton.AltText"]">
</div>
</div>




and i want to extract all the variable values of @ViewData - so for this example i would like to get a matches list containing:

"PageTitle"
"Excerpt"
"Template.HeaderButton.Url"
"Template.HeaderButton.Text"
"Template.HeaderButton.Image"
"Template.HeaderButton.AltText"


My best effort so far was to use this:
Regex regex = new Regex(@"""[^""\\]*(?:\\.[^""\\]*)*""");
to extract all string values (between speech marks) but this got confused with some values, i need to search for
@ViewData["GET_THIS_BIT_AS_A_MATCH"]


Tried this:
@"""[^@ViewData\[""\\]*(?:\\.[^""\]\\]*)*"""


But no luck! I am a bit of a RegeX noob!!! Can anyone help?

Thanks!

Answer

If you just want the values within @ViewData, I think this pattern will do what you need: @ViewData\[\"(.*?)\"\]. The value will be the capture group.