开发者

Extract string from string using Regex

I want to extract MasterPage value directive from a view page. I want the fastest way to do that, taking into account a very big aspx pages, and a very small ones.

I think the best way is to do that with two stages:

  1. Extract the page directive section from the view (using Regex):

    <%@ 开发者_开发百科Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

  2. Then, extract the value inside MasterPageFile attribute.

The result needs to be: ~/Views/Shared/Site.Master.

Can I have help from someone to implement this? I badly want to use only regex, but I don't Regex expert.

Another thing, Do you think that Regex is the fastest way to do this?


Here is a Regex that matches the Page directive and will have the value of the MasterPageFile attribute in group 1:

<%@\s?Page.*?MasterPageFile="([^"]+)".*?%>$

Why do you need it ? If you need to know the MasterPageFile when displaying the Page at runtime, there are easier and faster ways to do it.


    string a = "<%@ Page Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" Inherits=\"System.Web.Mvc.ViewPage\" %>";

    Regex r = new Regex("<%@.*MasterPageFile=\"([^\"]*)\".*%>", RegexOptions.Compiled);
    Match m = r.Match(a);
    if (m.Success)
    {
       // what you want is in m.Groups[1]
    }

Groups is an array of strings containing the parts of the match. Groups[0] is the whole match, and the rest will be everything contained within parentheses in your regex. So above, I surrounded the part you want with parentheses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜