【问题标题】:Print all substrings of a regex打印正则表达式的所有子字符串
【发布时间】:2019-11-18 10:34:13
【问题描述】:

我正在尝试打印我在文本中找到的所有子字符串。问题是 findall() 不发回子字符串,而是匹配捕获('H','dog')。我希望它发回一个字符串,例如“她的狗吃”

text = open("text_file_thing.txt", "r")
regex_string = "(H|h)er\s+(dog|cat|bird)\s+\w+"
regex = re.compile(regex_string)
match_array = regex.findall(text.read())
print(match_array)

我们将不胜感激。

【问题讨论】:

  • 我假设text 是一个多行文件?并且你想在匹配发生时返回整行吗?
  • 一旦正则表达式匹配并消耗了文本的一部分,它就不会重新访问它。
  • @PyPingu 我只想要子字符串,而不是整行。它是一个多行文件。

标签: python regex python-3.x string printing


【解决方案1】:

您可以改用re.finditer

import re

text = "Her dog eats. Her bird eats."
regex_string = "(H|h)er\s+(dog|cat|bird)\s+\w+"
regex = re.compile(regex_string)
for x in regex.finditer(text):
    print(x)

给予:

<re.Match object; span=(0, 12), match='Her dog eats'>
<re.Match object; span=(14, 27), match='Her bird eats'>

【讨论】:

    【解决方案2】:

    好的,所以我认为问题在于您使用findall,它只返回匹配部分的元组。 如果您使用finditer,您可以获得整个匹配对象。

    试试这个:

    import re
    text = open("text_file_thing.txt", "r")
    regex_string = "(H|h)er\s+(dog|cat|bird)\s+\w+"
    regex = re.compile(regex_string)
    match_array = regex.finditer(text.read())
    
    # Now you can either just loop through the iterator or
    # convert it to a list if you need to keep the objects and not 
    # just print them
    match_list = list(match_array)
    
    for m in match_list:
        print(m.string)
    

    【讨论】:

      【解决方案3】:

      您定义捕获组。使用非捕获组来获得整个匹配:

      import re
      
      text = """Her pig groans
      Her    dog swoons.
      her bird feeds.
      Her cat purrs."""
      regex_string = "(?:H|h)er\s+(?:dog|cat|bird)\s+\w+"
      regex = re.compile(regex_string)
      match_array = regex.findall(text)
      print(match_array)
      

      输出:

      ['Her    dog swoons', 'her bird feeds', 'Her cat purrs']
      

      见:

      re documentation

      (?:...):正则括号的非捕获版本。火柴 括号内的任何正则表达式,但 组匹配的子字符串在执行后无法检索 匹配或稍后在模式中引用。

      【讨论】:

        猜你喜欢
        • 2012-08-16
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        • 2011-10-02
        相关资源
        最近更新 更多