Regular Expression

Soldato
Joined
14 Feb 2004
Posts
14,315
Location
Peoples Republic of Histonia, Cambridge
How would i write a regular expression in C# to match just the inner text of the following html tag <span id="name">Inner Text</span>

So I'd want the first match to be "Inner Text"
 
Last edited:
know the answer should be along the lines of <span id="name">(.*?)</span> but it dosen't work :(
 
Last edited:
try this

<span id="name">[^<]*

the one youve already quoted should have done it, gotta love reg expressions :)
The example I've given matches the whole string i.e. <span id="name">Inner Text</span> where as I just want the Inner Text part. I thought the brackets normally act as a separate "sub" match pattern??? This is getting very annoying!!
 
This is the test code I have set up

Code:
string text = "<span id=\"name\">Inner Text</span>";

Regex testRegex = new Regex("<span id=\"name\">(.*?)</span>");

MatchCollection matches = testRegex.Matches(text);

this.txtInfo.AppendText("Number of matches = " + matches.Count + Environment.NewLine);

foreach (Match match in matches)
{
       this.txtInfo.AppendText("Matches = " + match.Value + Environment.NewLine);
}

Am I missing something?
 
I've figured it out. You need to use the RegEx.Match.Groups collection to access the captured groups. Can't belive how long it's taken me to work that out :o

I guess that's what you get for trying to program after 20 hours without sleep. It's a long one tomorrow too, best get to bed :(
 
I've figured it out. You need to use the RegEx.Match.Groups collection to access the captured groups. Can't belive how long it's taken me to work that out :o

I guess that's what you get for trying to program after 20 hours without sleep. It's a long one tomorrow too, best get to bed :(

Nice one, I was just going to post this I got this working in VB.NET (Loads of VB to C# converters out there) for you: -

Code:
  Dim inputString As String

        inputString = "<span id=""name"">Isssssnner Text</span>"
        Dim resultString As String

        Dim r As New Regex("<span id=""name"">(?<name>.*?)</span>")
        resultString = r.Match(inputString).Groups("name").ToString

        Response.Write("Result is: " & resultString)
 
Back
Top Bottom