Emulating possessive quantifiers

我怕爱的太早我们不能终老 提交于 2019-12-18 04:35:09

问题


Is it possible to emulate possessive quantifiers (.NET doesn’t support it) using atomic grouping (or in other way)?

Note. I found that (x+x+)++y can be replaced with (?>(x+x+)+)y, but this is just an example and I don’t know whether always {something}@+ equals to (?>{something}@) (where @ is a quantifier).


回答1:


Yup. May I quote the master himself, Jeffrey Friedl, from page 142 of his classic Mastering Regular Expressions (3rd Edition):

"In one sense, possessive quantifiers are just syntactic sugar, as they can be mimicked with atomic grouping. Something like .++ has exactly the same result as (?>.+), although a smart implementation can optimize possessive quantifiers more than atomic grouping."




回答2:


Nope, that's all there is to it. Possessive quantifiers are just a convenient shorthand for atomic groups.

Now, if you were using a flavor that doesn't support atomic groups either (like JavaScript and Python), you could use a lookahead to get the same effect:

(?=((x+x+)+))\1y

A lookahead works just like an atomic group except that it doesn't consume what it matches. So you wrap its contents in a capturing group, then use a backreference to do the consuming.



来源:https://stackoverflow.com/questions/5537513/emulating-possessive-quantifiers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!