1

I have an ASP.net string, and I am trying to extract ID from it. Here is the code:

public static string getName(string line)
{
    string ret = "";

    if (!line.Contains("ID="))
        return ret;
    var regex = new Regex("/.*ID=\".*?\".*/g");
    if (regex.IsMatch(line))
        ret = regex.Match(line).Groups[1].Value;
    return ret;
}

And regex.IsMatch(line) always returns false.

2
  • Perhaps you could add an example were the regex is not working ? Commented Feb 14, 2014 at 11:58
  • For example, this line : <asp:Label ID="lbl_QV4" runat="server" Text="&rarr; QV5"></asp:Label> Commented Feb 14, 2014 at 12:01

2 Answers 2

7

You didn't do the grouping at your regex. Here it is

var regex = new Regex("/.*ID=\"(.*?)\".*/g");
                               ^   ^

Update: The way you are matching the regex is not correct. Here is how it works.

var regex = "ID=\"(.*?)\"";
if ( Regex.IsMatch(line, regex) ){
    ret = Regex.Match(line, regex).Groups[1].Value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Solved it. Workiing code is :

public static string getName(string line)
        {
            string ret = "";

            if (!line.Contains("ID="))
                return ret;
            var regex = ".*ID=\"(.*?)\".*";
            if (Regex.IsMatch(line, regex) )
                ret = Regex.Match(line, regex).Groups[1].Value;
            return ret;
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.