最左边的最长匹配(分离) [英] leftmost longest match (of disjunctions)

查看:93
本文介绍了最左边的最长匹配(分离)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,


下面给出的程序返回以下行:


a

ab


有没有办法使用python正则表达式,这样程序

会返回以下行?


ab

ab


############################### #########################################

import re


rx1 = re.compile("(a | ab)")

rx2 = re.compile("( ab | a)")


out1 = rx1.search(" ab")

out2 = rx2.search(" ab")


打印out1.group(1)

打印out2.group(1)


##### ################################################## #################

J?rg

Hello,

The program given below returns the lines:

a
ab

Is there a way to use python regular expressions such that the program
would return the following lines?

ab
ab

################################################## ######################

import re

rx1 = re.compile("(a|ab)")
rx2 = re.compile("(ab|a)")

out1 = rx1.search("ab")
out2 = rx2.search("ab")

print out1.group(1)
print out2.group(1)

################################################## ######################

J?rg

推荐答案

Joerg Schuster写道:
Joerg Schuster wrote:

下面给出的程序返回行:

a


有一种方法来使用pyt正则表达式,使程序
将返回以下行?

ab

########### ################################################### ###########



rx1 = re.compile("(a | ab)")
rx2 = re.compile("(ab | a)")

The program given below returns the lines:

a
ab

Is there a way to use python regular expressions such that the program
would return the following lines?

ab
ab

################################################## ######################

import re

rx1 = re.compile("(a|ab)")
rx2 = re.compile("(ab|a)")




您是否检查了文档re?


它的内容如下:

" |" A | B,其中A和B可以是任意RE,创建一个正则表达式

,它将匹配A或B.任意数量的RE可以分开

by |通过这种方式。这也可以在组内部使用(见下文)。

当扫描目标字符串时,RE由|分隔。从左边开始试试

吧。当一个模式完全匹配时,接受该分支。这个

意味着一旦A匹配,B将不会被进一步测试,即使它会产生更长的整体匹配。换句话说,|,|。操作员永远不会贪得无厌。


------


对我来说看起来很清楚明了。你的例子基本上是上面代码的工作证明,所以我不确定你的期望是什么。


-Peter


Peter Hansen< pe *** @ engcorp.com>写道:
Peter Hansen <pe***@engcorp.com> writes:
产生更长的整体匹配。换句话说,|,|。操作员永远不会贪婪。
produce a longer overall match. In other words, the "|" operator is never
greedy.




O.k.感谢您指出了这一点。也许我应该以不同的方式制定我的

问题:是否有诀窍(无论是否肮脏)

" |"蟒蛇贪婪?

J?rg



O.k. Thanks for pointing this out. Maybe I should have formulated my
question differently: Is there a trick (be it dirty or not) to make
"|" greedy in python?
J?rg


Peter Hansen< pe *** @ engcorp.com>写道:
Peter Hansen <pe***@engcorp.com> writes:
产生更长的整体匹配。换句话说,|,|。操作员永远不会贪婪。
produce a longer overall match. In other words, the "|" operator is never
greedy.




O.k.感谢您指出了这一点。也许我应该以不同的方式制定我的

问题:是否有诀窍(无论是否肮脏)

" |"蟒蛇贪婪吗?

J?rg



O.k. Thanks for pointing this out. Maybe I should have formulated my
question differently: Is there a trick (be it dirty or not) to make
"|" greedy in python?
J?rg


这篇关于最左边的最长匹配(分离)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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