简体   繁体   English

为什么这个简单的REGEX不起作用?

[英]Why isn't this simple REGEX working?

http://jsfiddle.net/C4K6c/ http://jsfiddle.net/C4K6c/

I'm trying to do a simple regex in JavaScript but it's not working. 我正在尝试用JavaScript做一个简单的正则表达式,但是它不起作用。

HTML: HTML:

<div id="content">
    <p><img class="inline-image" src="1.jpg" data-frame="full" alt="" /></p>
    <p><img class="inline-image" src="2.jpg" data-frame="half" /></p>
    <p><img src="2.jpg" /></p>    
</div>

JS: JS:

var content = document.getElementById('content').innerHTML,
    matches = content.match(/<img(.+)data-frame(.+)>/);

for(var i=0; i < matches.length; i++) {
    alert( matches[i] )
}

I am not getting back what I am expecting, which is this: 我没有得到我所期望的,这是:

<img class="inline-image" src="2.jpg" data-frame="half" />
<img class="inline-image" src="1.jpg" data-frame="full" alt="" />

Add the g flag and avoid the closing > to avoid having </p> in your match. 添加g标志并避免使用>来避免匹配中出现</p> And to avoid other problems if your HTML can be more diverse, you should also change the first .+ : 为了避免其他问题(如果您的HTML可以更多样化),还应该更改第一个.+

matches = content.match(/<img([^>]+)data-frame([^>]+)>/g);

Demonstration 示范

Try to make it non-greedy and the DOTALL work-around: 尝试使其不贪心并解决DOTALL:

matches = content.match(/<img([\s\S]+?)data-frame([^>]*)>/ig);

I also added global and ignore case switch. 我还添加了globalignore case切换。

http://jsfiddle.net/C4K6c/3/ http://jsfiddle.net/C4K6c/3/

As much as I love regex, I highly recommend using the DOM to your advantage here. 尽管我很喜欢正则表达式,但我强烈建议您在这里使用DOM来发挥自己的优势。

var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
var final = [];
for (var i = 0; i< images.length; i++)
    if (images[i].hasAttribute("data-frame"))
        final.push(images[i]);

This algorithm has the advantage of being self documenting. 该算法具有自我记录的优势。 It's also probably faster than using a regular expression. 它也可能比使用正则表达式更快。

我不了解Java,但通常需要像这样转义符号<>:

matches = content.match(/\<img(.+)data-frame(.+)\>/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM