是否有Perl相当于Python的re.findall / re.finditer(迭代正则表达式结果)? [英] Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)?

查看:107
本文介绍了是否有Perl相当于Python的re.findall / re.finditer(迭代正则表达式结果)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python编译的正则表达式模式中 findall 方法

In Python compiled regex patterns have a findall method that does the following:


返回
模式的所有非重叠匹配string,作为
字符串的列表。从左到右扫描字符串
,匹配是在找到的订单中返回的
。如果
模式中存在一个或
个更多组,则返回组列表;如果
模式有多个组,则
将是元组列表。空
匹配包含在结果
中,除非他们触及
另一场比赛的开头。

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

在Perl中执行此操作的规范方法是什么?我能想到的一个天真的算法是当搜索并用空字符串替换成功时,做[套件]。我希望有一个更好的方式。 : - )

What's the canonical way of doing this in Perl? A naive algorithm I can think of is along the lines of "while a search and replace with the empty string is successful, do [suite]". I'm hoping there's a nicer way. :-)

提前致谢!

推荐答案

使用 / g 匹配中的修饰符。从 perlop 手册:

Use the /g modifier in your match. From the perlop manual:


/ g 修饰符指定全局模式匹配 - 即在字符串中尽可能多地匹配。它的行为取决于上下文。在列表上下文中,它返回正则表达式中任何捕获括号匹配的子字符串列表。如果没有括号,则返回所有匹配字符串的列表,就好像整个模式周围都有括号一样。

The "/g" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.

在标量上下文中,每次执行 m // g 找到下一个匹配项,如果匹配则返回true,如果没有进一步匹配则返回false。可以使用 pos()函数读取或设置最后一次匹配后的位置;请参阅 perlfunc 中的 pos 。失败的匹配通常会将搜索位置重置为字符串的开头,但您可以通过添加 / c 修饰符来避免这种情况(例如米// GC )。修改目标字符串也会重置搜索位置。

In scalar context, each execution of "m//g" finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the pos() function; see "pos" in perlfunc. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the "/c" modifier (e.g. "m//gc"). Modifying the target string also resets the search position.

这篇关于是否有Perl相当于Python的re.findall / re.finditer(迭代正则表达式结果)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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