如何用正则表达式查找所有的猫

2024-06-16 13:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到所有带有正则表达式的“猫”?在

"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems!" (c) Jamie Zawinski

请帮助我用一个查询查找divs中的所有“cat”:)

cat
<div>let's try to find this cat and this cat</div>
cat
<div>let's try to find this cat and this cat</div>
cat

我本来是这么做的,但没用:

^{pr2}$

Regular expression visualization

Debuggex Demo

我在使用崇高文本时发现了这个问题。我们只能进行一次查询。有可能吗?如果你能用任何编程语言(Python、PHP、JavaScript)回答,我也很高兴。谢谢您!在

我可以找到最后一只猫,也可以找到第一只,但需要找到所有坐在沙发上的猫。我想其他语言的东西也有可能,但我只想要一个查询(一行)——这对我来说最有趣。如果这是不可能的,对不起我的帖子:)

感谢@revo!非常好的变体,在崇高的文本中工作。 让我为这个主题添加第二个问题。。。 我们能为“猫”类的女主角做这件事吗,但不能为“狗”类的女主角做呢?在

cat
<div class="cats">black cat, white cat</div>
cat
<div class="dogs">black cat, white cat</div>
cat

Tags: andto文本divsomefindthispeople
3条回答

考虑到您没有指定它需要使用哪种语言,我将在这个解决方案中使用JavaScript。在

你可以用一个简单的技巧来做,那就是清除所有垃圾:

var string = "<div>let's try to find this cat and this cat</div>\n<div>let's try to find this cat and this cat</div>\nanother cat";
var str = string.replace(/(^|<\/div>)[\w\W]*?(<div>|$)/g,''); //filters out anything outside divs
console.log(str.match(/cat/g)); // ["cat", "cat", "cat", "cat"]

在一行中,这将是:

^{pr2}$

即使您需要匹配以下内容,也可以使其正常工作:

<div class="foo"><div></div>cat</div>

我会使用以下方法:

var str = "<div>let's try to find this cat and this cat</div>\n<div>let's try to find this cat and this cat</div>\nanother cat\n<div class=\"foo\"><div></div>and a cat</div>";
var openCounter = 0;
var result = [];
for (var i=0;i<str.length;i++) {
    if (str.substr(i,4) == '<div') openCounter++;
    else if (str.substr(i,6) == '</div>') openCounter = Math.max(0,openCounter-1); //don't go lower than 0
    if (openCounter > 0 && str.substr(i,3) == 'cat') result.push([str.substr(i,3), i]);
}
console.log(JSON.stringify(result)); //[["cat",28],["cat",41],["cat",79],["cat",92],["cat",148]]

它还获取在字符串中找到cat的索引,并将它与cat一起存储在result变量中。在

这对崇高的文本起作用:

(?s)(cat)(?=[^>]*?</div>)

Sublime

PHP模式:

$pattern = '~(?><div\b[^>]*+>|\G(?<!^))(?>[^c<]++|\Bc|c(?!at\b)|<(?!/div>))*+\Kcat~';
preg_match_all($pattern, $subject, $matches);
print_r($matches);

图案细节:

^{pr2}$

使用DOM:

$dom = new DOMDocument();
@$dom->loadHTML($yourHtml);
$divs = $dom->getElementsByTagName('div');
foreach($divs as $div) {
    preg_match_all('~\bcat\b~', $div->textContent, $matches);
    print_r($matches);
}

相关问题 更多 >