开发者

JavaScript lazy regex for matching HTML tags

开发者 https://www.devze.com 2023-01-04 06:01 出处:网络
I\'m having a problem writing a regular expression for matching HTML tags. I found a similar entry here, but this didn\'t quite work in my case.

I'm having a problem writing a regular expression for matching HTML tags. I found a similar entry here, but this didn't quite work in my case.

Here's my test string:

<div id="div0" class="myclass">here's some text
that may include whitespace</div><div id="div1" class="myclass">
and some more here
</div>

And here's my regex based on the aforementioned entry:

<div[^>]*class="myclass">[^~]*?<\/div>

Note that I nee开发者_StackOverflowd to match the first instance of <div /> with class of "myclass." The content may have carriage returns. These <div> tags won't be nested.

Here's a rubular page for testing: http://rubular.com/r/vlfcikKMXk


That regex tested is not great. It is in fact matching as you want it to, but it is matching it multiple times (2 different matches), and not showing a difference, you only want the first match.

Go here: http://gskinner.com/RegExr/

Test it there, turn off the 'global' you will see it working.

0

精彩评论

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