簡體   English   中英

我可以在python中用幾個正則表達式的並集擴展單個字符串嗎?

[英]Can I expand a single string with the union of several regular expressions in python?

我正在破解一個可以轉換文件類型的程序包 ,允許用戶指定轉換(python函數)和用於更改文件名的正則表達式。

在一種情況下,我有一系列正則表達式和一個輸出字符串,我希望通過所有正則表達式組的並集來對其進行擴展:

import re
re_strings = ['(.*).txt', '(.*).ogg', 'another(?P<name>.*)']
regexes = map(re.compile, re_strings]
input_files = ['cats.txt', 'music.ogg', 'anotherpilgrim.xls']
matches = [regexes[i].match(input_files[i]) for i in range(len(regexes))]

outputstr = 'Text file about: \1, audio file about: \2, and another file on \g<name>.'
# should be 'Text file about: cats, audio file about: music, and another file on pilgrim.xls'

我想用正則表達式的並集來擴展outputstr (也許對於\\2引用來說,串聯更有意義嗎?)。 我可以將re連接起來,並用一些未使用的字符將它們分開:

final_re = re.compile('\n'.join(re_strings))
final_files = '\n'.join(input_files)
match = final_re.search(final_files)

但這迫使re匹配整個文件,而不僅僅是文件名的一部分。 我可以在文件la (.*?)之間放置一個包羅萬象的組,但這肯定會弄亂組引用,並且可能會弄亂原始模式(我無法控制)。 我想我也可以在任何地方強制命名組,然后合並所有正則表達式.groupdict()s ...

Python不允許部分擴展,因此所有組引用都必須有效,因此無論如何都不可能對groupdict進行一系列擴展,例如:

for m in matches:
    outputstr = m.expand(outputstr)

感謝您的任何建議!

僅作記錄,這里是如何組合多個正則表達式結果的結果,並在所有結果之間進行替換。

給定幾個查詢字符串和幾個正則表達式匹配項:

import re

query_str = ["abcdyyy", "hijkzzz"]
re_pattern = [r"(a)(b)(?P<first_name>c)(d)",
              r"(h)(i)(?P<second_name>j)(k)"]

# match each separately
matches= [re.search(p,q) for p,q in 
          zip(re_pattern, query_str)]

我們要創建一個替換字符串,將所有搜索的結果結合起來:

replacement = r"[\4_\g<first_name>_\2_\1:\5:\6:\8:\g<second_name>]"

為此,我們需要:

  1. 合並搜索結果
  2. 用代理代替合並結果(match_substitute)
  3. 有一個代理對象來處理命名組,例如“ first_name”(pattern_substitute)

這由以下代碼處理。 結果在“結果”中:

import sre_parse

#
#   dummy object to provide group() function and "string" member variable
#
class match_substitute:
    def __init__(self, matches): 
        self.data = []
        for m in matches:
            self.data.extend(m.groups())
        self.string = ""
    # regular expression groups count from 1 not from zero!
    def group(self, ii):
        return self.data[ii - 1]



#
#   dummy object to provide groupindex dictionary for named groups
#
class pattern_substitute:
    def __init__(self, matches, re_pattern): 
        #
        #   Named group support
        #   Increment indices so they are point to the correct position
        #       in the merged list of matching groups
        #
        self.groupindex = dict()
        offset = 0
        for p, m in zip(re_pattern, matches):
            for k,v in sre_parse.parse(p).pattern.groupdict.iteritems():
                self.groupindex[k] = v + offset
            offset += len(m.groups())



match   = match_substitute(matches)
pattern = pattern_substitute(matches, re_pattern)

#
#   parse and substitute
#
template = sre_parse.parse_template(replacement, pattern)
result = sre_parse.expand_template(template, match)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM