問題描述
在 Python 編譯的正則表達式模式中有一個 findall
方法 執行以下操作:
In Python compiled regex patterns have a findall
method that does the following:
返回所有不重疊的匹配項字符串中的模式,作為列表字符串.字符串被掃描從左到右,匹配是按找到的順序返回.如果一個或更多的群體出現在模式,返回組列表;這將是一個元組列表,如果模式有多個組.空的匹配項包含在結果中除非他們觸及另一場比賽.
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 中執行此操作的規范方法是什么?我能想到的一個天真的算法是當搜索并用空字符串替換成功時,執行 [suite]".我希望有更好的方法.:-)
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
"修飾符來避免這種情況(例如m//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.
這篇關于是否有 Python 的 re.findall/re.finditer(迭代正則表達式結果)的 Perl 等價物?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!