最左边的最长匹配(分离)

编程入门 行业动态 更新时间:2024-10-17 00:27:17
本文介绍了最左边的最长匹配(分离)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好, 下面给出的程序返回以下行: a ab 有没有办法使用python正则表达式,这样程序 会返回以下行? ab ab ############################### ######################################### import re rx1 = repile("(a | ab)") rx2 = repile("( 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 = repile("(a|ab)") rx2 = repile("(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 = repile("(a | ab)") rx2 = repile("(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 = repile("(a|ab)") rx2 = repile("(ab|a)")

您是否检查了文档re? 它的内容如下: " |" A | B,其中A和B可以是任意RE,创建一个正则表达式 ,它将匹配A或B.任意数量的RE可以分开 by |通过这种方式。这也可以在组内部使用(见下文)。 当扫描目标字符串时,RE由|分隔。从左边开始试试 吧。当一个模式完全匹配时,接受该分支。这个 意味着一旦A匹配,B将不会被进一步测试,即使它会产生更长的整体匹配。换句话说,|,|。操作员永远不会贪得无厌。 ------ 对我来说看起来很清楚明了。你的例子基本上是上面代码的工作证明,所以我不确定你的期望是什么。 -Peter

Peter Hansen< pe *** @ engcorp>写道: Peter Hansen <pe***@engcorp> 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>写道: Peter Hansen <pe***@engcorp> 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

更多推荐

最左边的最长匹配(分离)

本文发布于:2023-10-26 18:33:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最长

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!