Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Specific Tag

Tags:

.net

regex

I'm working on a regular expression in a .NET project to get a specific tag. I would like to match the entire DIV tag and its contents:

<html>
   <head><title>Test</title></head>
   <body>
     <p>The first paragraph.</p>
     <div id='super_special'>
        <p>The Store paragraph</p>
     </div>
     </body>
  </head>

Code:

    Regex re = new Regex("(<div id='super_special'>.*?</div>)", RegexOptions.Multiline);


    if (re.IsMatch(test))
        Console.WriteLine("it matches");
    else
        Console.WriteLine("no match");

I want to match this:

<div id="super_special">
   <p>Anything could go in here...doesn't matter.  Let's get it all</p>
</div>

I thought . was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?

Thanks.

like image 801
Bullines Avatar asked Jun 11 '26 12:06

Bullines


2 Answers

Please, pretty please, do yourself a huge favor: use an HTML parser for parsing HTML. Seriously. That's what they are there for.

HTML is a very complex language. No matter how long you will be tweaking, fiddling, fixing, honing your Regexp, there will always be a case you're missing.

Anyway, you have to tell your Regexp engine to match multiple lines instead of just one. In some of the most popular ones you do that by applying the /m modifier.

But let me repeat: please use an HTML parser. Everytime someone uses a Regexp to parse HTML, a kitten dies ...

like image 173
Jörg W Mittag Avatar answered Jun 13 '26 04:06

Jörg W Mittag


Out-of-the-box, without special modifiers, most regex implementations don't go beyond the end-of-line to match text. You probably should look in the documentation of the regex engine you're using for such modifier.

I have one other advice: beware of greed! Traditionally, regex are greedy which means that your regex would probably match this:

<div id="super_special">
  I'm the wanted div!
</div>
<div id="not_special">
  I'm not wanted, but I've been caught too :(
</div>

You should check for a "not-greedy" modifier, so that your regex would stop matching text at the first occurence of </div>, not at the last one.

Also, as others have said, consider using an HTML parser instead of regexes. It will save you a lot of headache.

Edit: even a non-greedy regex wouldn't work as expected either, if <div>s are nested! Another reason to consider using an HTML parser.

like image 24
André Chalella Avatar answered Jun 13 '26 03:06

André Chalella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!