【问题标题】:Python to search and print out the whole line just like Linux grep?Python 像 Linux grep 一样搜索并打印出整行?
【发布时间】:2020-07-03 15:20:00
【问题描述】:

让我们以此为例。

>>> t = '''Line 1
... Line 2
... Line 3'''
>>> 

re.findall只打印出类似于Linux grep -o的特定模式

>>> re.findall('2', t)
['2']
>>> 

Linux grep

wolf@linux:~$ echo 'Line 2' | grep 2
Line 2
wolf@linux:~$ 

Linux grep -o

wolf@linux:~$ echo 'Line 2' | grep 2 -o
2
wolf@linux:~$ 

我知道可以打印出整个输出,我只是暂时想不出其中的逻辑。

Python 中的预期输出

Line 2

如果有更好的方法,请告诉我。

【问题讨论】:

  • 做 grep 做的事。将输入拆分为行,打印与模式匹配的行。

标签: python linux search python-re


【解决方案1】:
print([l for l in t.splitlines() if "2" in l])

或者,如果你想像grep那样分开,

print('\n'.join([l for l in t.splitlines() if "2" in l]))

【讨论】:

    【解决方案2】:

    将 .* 放在要查找的内容周围:

    re.findall(r'.*2.*', t)  
    

    【讨论】:

    • 谢谢,它有效。为你+1。顺便说一句,r 是什么意思?
    • @Wolf - r'...' 是原始字符串。 docs.python.org/3/reference/…
    • 表示原始字符串。例如,如果你放了一个 \,它意味着一个 \ 字符并且不被解释为一个转义字符。出于习惯,在使用正则表达式时,即使不需要,我也总是放 r。
    【解决方案3】:
    t = '''Line 1
    Line 2
    Line 3'''
    
    for line in t.split('\n'):
        if(line.find("2")!=-1):
            print(line)
    

    这应该适用于您的用例。 find() 用于检查字符串中是否存在模式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2012-11-02
      相关资源
      最近更新 更多