正则表达式从左侧不贪婪(即两侧可能的最窄匹配)
假设我正在尝试将 /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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 前瞻性断言 来排除
dog< 的出现
dog
和lab
之间的 /code>:You could use a look-ahead assertion that excludes the occurrence of
dog
betweendog
andlab
:这对我有用:
This works for me:
一个想法可能是尝试使用否定字符集,例如
[^.!?]
,它将匹配除.
、?
和!
,因此您可以确定它在同一个句子中: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: