Jorje Redemption Jorje Redemption - 1 year ago 34
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>
<a class="btn btn-primary btn-lg" href="@ViewData["Template.HeaderButton.Url"]" role="button">@ViewData["Template.HeaderButton.Text"]</a>
<div class="col-md-5">
<img class="featurette-image img-responsive center-block" src="@ViewData["Template.HeaderButton.Image"]" alt="@ViewData["Template.HeaderButton.AltText"]">

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


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

Tried this:

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


Answer Source

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.