【问题标题】:Python - Regex - match characters between certain charactersPython - 正则表达式 - 匹配某些字符之间的字符
【发布时间】:2019-05-09 01:08:49
【问题描述】:

我有一个文本文件,我想匹配/查找/解析某些字符之间的所有字符([\n" 要匹配的文本 "\ n])。文本本身在其包含的结构和字符方面可能存在很大差异(它们可以包含所有可能的字符)。

我之前发布了这个问题(抱歉重复),但到目前为止问题无法解决,所以现在我试图更准确地解决这个问题。

文件中的文本是这样构建的:

    test =""" 
        [
        "this is a text and its supposed to contain every possible char."
        ], 
        [
        "like *.;#]§< and many "" more."
        ], 
        [
        "plus there are even
newlines

in it."
        ]"""

我想要的输出应该是一个列表(例如),将分隔符之间的每个文本作为一个元素,如下所示:

['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.', 'plus there are even newlines in it.']

我尝试使用正则表达式和两个解决方案以及我想出的相应输出来解决它:

my_list = re.findall(r'(?<=\[\n {8}\").*(?=\"\n {8}\])', test)
print (my_list)

['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.']

好吧,这个很接近。它列出了前两个元素,但不幸的是,它没有列出第三个元素,因为它里面有换行符。

my_list = re.findall(r'(?<=\[\n {8}\")[\s\S]*(?=\"\n {8}\])', test)
print (my_list)

['this is a text and its supposed to contain every possible char."\n        ], \n        [\n        "like *.;#]§< and many "" more."\n        ], \n        [\n        "plus there are even\nnewlines\n        \n        in it.']

好吧,这次包含了每个元素,但列表中只有一个元素,并且前瞻似乎没有像我想象的那样工作。

那么,什么是正确的正则表达式来获得我想要的输出? 为什么第二种方法不包括前瞻?

或者是否有更清洁、更快捷的方法来获得我想要的东西(beautifulsoup 或其他方法?)?

我非常感谢任何帮助和提示。

我正在使用 python 3.6。

【问题讨论】:

  • 您的预期输出在字符串中有“newlins” - 我假设这是一个错字,您的意思是“newlines”,对吧?
  • 是的,你说得对。谢谢。

标签: python regex character match findall


【解决方案1】:

您应该使用DOTALL 标志来匹配换行符

print(re.findall(r'\[\n\s+"(.*?)"\n\s+\]', test, re.DOTALL))

输出

['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.', 'plus there are even\nnewlines\n\nin it.']

【讨论】:

    【解决方案2】:

    你可以使用模式

    (?s)\[[^"]*"(.*?)"[^]"]*\]
    

    捕获括号内"s 内的每个元素:

    https://regex101.com/r/SguEAU/1

    然后,您可以使用带有re.sub 的列表推导来用单个普通空格替换每个捕获的子字符串中的空白字符(包括换行符):

    test ="""
        [
        "this is a text and its supposed to contain every possible char."
        ],
        [
        "like *.;#]§< and many "" more."
        ],
        [
        "plus there are even
    newlines
    
    in it."
        ]"""
    
    output = [re.sub('\s+', ' ', m.group(1)) for m in re.finditer(r'(?s)\[[^"]*"(.*?)"[^]"]*\]', test)]
    

    结果:

    ['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.', 'plus there are even newlines in it.']
    

    【讨论】:

    • 感谢您的正则表达式在示例中工作得很好。只有当我在我的文本文件上尝试它时,它有时会在捕获文本时出现问题,当其中有带有引号的模式时。但是,您对列表理解的提示也非常有帮助。我将它与 Krishna 的方法结合起来,它似乎在我的文本文件上运行良好。
    • 我很好奇,正则表达式失败的输入是什么? s 标志加上 .*? 应该考虑到所有情况,我想
    猜你喜欢
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多