【问题标题】:Regex - Print the lines starting with a T正则表达式 - 打印以 T 开头的行
【发布时间】:2015-10-23 13:05:04
【问题描述】:

我有一个包含一些行的文本文件,我想打印以 T 开头的行。

这有效并给出了所需的输出:

f = open("path", 'r')
for line in f:
    match = re.search(r'^T', line)
    if match:
        print line

但这并没有按预期工作,它会打印一个空列表[],而不是包含以T开头的行的数组:

f1 = open("path").read()
print re.findall(r'^T', f1)

第二个解决方案的错误在哪里?

【问题讨论】:

  • 你需要re.MULTILINE 来匹配^ 来匹配lines 的开始,而不仅仅是string 的开始。
  • print re.findall(r'(?m)^T', f1)
  • 这里是some code 说明re.M 修饰符的使用。
  • 是同一个修饰符,一个是内联的,一个是非内联的。
  • @Borja “更好” 怎么样?我发现前者更具可读性,但这只是一种观点,我怀疑性能会有所不同。

标签: python regex python-2.7


【解决方案1】:

要使^ 匹配每一行的开头,而不仅仅是整个字符串,您需要使用MULTILINE flag。您可以在正则表达式本身中执行此操作:

re.findall('(?m)^T', ...)

或作为flags 参数:

re.findall('^T', ..., flags=re.M)  # M is an alias for MULTILINE

请注意,这将为您提供'T's - 将其余行包含在您需要添加的匹配项中,例如.* 到模式。

快速演示:

>>> import re
>>> text = """Here is some demo text
This line starts with a T
But this one doesn't
That's OK"""
>>> re.findall('^T', text)
[]  # no multiline match, no results
>>> re.findall('^T', text, re.M)
['T', 'T']  # multiline match, only T in the results
>>> re.findall('^T.*', text, re.M)
['This line starts with a T', "That's OK"]  # hooray!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2014-06-04
    • 2018-03-08
    相关资源
    最近更新 更多