如何匹配满足我的正则表达式模式的最短字符序列? [英] How can I match the shortest possible sequence of characters that satisfy my regex pattern?

查看:53
本文介绍了如何匹配满足我的正则表达式模式的最短字符序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"ajjjjjjjjjaab"

我想要一个匹配最后一个"ab"而不是整个字符串甚至"aab"的模式.

I want a pattern which will match the last "ab" and not the whole string or even "aab".

/a.*?b/  # returns two groups

/a.??b/ # matches last aab

都不行.

推荐答案

其中之一:

/a[^a]*b/
/a[^ab]*b/


如果ab实际上是更复杂的模式,则可以使用以下内容:


If a and b are actually more complex patterns, one can use the following:

/a(?:(?!a).)*b/s
/a(?:(?!a|b).)*b/s


如果ab表示长而复杂的模式,则可以避免像使用任何其他代码一样使用变量来重复它们.


If a and b represent long/complex patterns, one can avoid repeating them using variables like in any other code.

my $re1 = qr/a/;
my $re2 = qr/b/;

/$re1(?:(?!$re1|$re2).)*$re2/s

一个人也可以使用子模式.

One can also use subpatterns.

/
   (?&A) (?:(?!(?&A)|(?&B)).)* (?&B)

   (?(DEFINE)
      (?<A> a )
      (?<B> b )
   )
/xs

这篇关于如何匹配满足我的正则表达式模式的最短字符序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆