正则表达式从左侧不贪婪(即两侧可能的最窄匹配)

发布于 2024-09-15 19:12:43 字数 380 浏览 6 评论 0原文

假设我正在尝试将 /dog.*lab/ 与此文本进行匹配:

“我有一只狗。我的狗是一只黑色实验室。他是在实验室中创建的。”< /em>

贪婪地,它会匹配“狗。我的狗是一只黑色实验室。他是在实验室中创建的”。

我想找到双方距离最窄的比赛。如果我使用像
这样的不贪婪修饰符 /dog.*?lab//dog.*lab/U 它将匹配较少但仍然太多:
“狗。我的狗是黑色拉布拉多犬”

有没有办法让我的搜索也从左侧变得不贪婪,从而只匹配“狗是黑色拉布拉多犬”?

非常感谢。很抱歉这个人为的例子。

Let's say I'm trying to match /dog.*lab/ against this text:

"I have a dog. My dog is a black lab. He was created in a laboratory."

Greedily, it would match "dog. My dog is a black lab. He was created in a lab".

I want to find the matches that are narrowest from both sides. If I use the ungreedy modifier like
/dog.*?lab/ or /dog.*lab/U it will match less but still too much:
"dog. My dog is a black lab"

Is there a way to make my search ungreedy from the left also, thus matching only "dog is a black lab"?

Much thanks. Sorry for the contrived example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光匆匆的小流年 2024-09-22 19:12:43

您可以使用 前瞻性断言 来排除 dog< 的出现doglab 之间的 /code>:

/dog(?:(?!dog).)*?lab/

You could use a look-ahead assertion that excludes the occurrence of dog between dog and lab:

/dog(?:(?!dog).)*?lab/
女中豪杰 2024-09-22 19:12:43

这对我有用:

$str = "I have a dog. My dog is a black lab. He was created in a laboratory.";
if(preg_match('/.*(dog.*?lab)/',$str,$m)) {
    var_dump($m);
}

This works for me:

$str = "I have a dog. My dog is a black lab. He was created in a laboratory.";
if(preg_match('/.*(dog.*?lab)/',$str,$m)) {
    var_dump($m);
}
此生挚爱伱 2024-09-22 19:12:43

一个想法可能是尝试使用否定字符集,例如 [^.!?],它将匹配除 .?!,因此您可以确定它在同一个句子中:

$string = "I have a dog. My dog is a black lab. He was created in a laboratory.";
preg_match('/dog[^.!?]*?lab/', $string, $match);
echo $match[0]; // Echoes "dog is a black lab"

An idea might be to try to use a negated character set, like [^.!?], which would match all characters except ., ? and !, and therefore you can be sure that it is within the same sentence:

$string = "I have a dog. My dog is a black lab. He was created in a laboratory.";
preg_match('/dog[^.!?]*?lab/', $string, $match);
echo $match[0]; // Echoes "dog is a black lab"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文