【问题标题】:Python re.match: How to specific "OR" matchPython re.match:如何进行特定的“或”匹配
【发布时间】:2019-04-04 10:26:16
【问题描述】:

假设我有一个数据文件:

# cat 1.txt
#$$!#@#VM - This is VM$^#^#$^$^
%#%$%^SAS - This is SAS&%^#$^$
!@#!@%^$^MD - This is MD!@$!@%$

现在我想过滤以VM和SAS开头的单词(不包括MD)

预期结果:

VM - This is VM
SAS - This is SAS

我正在使用此代码,但显示所有行。

import re

f = open("1.txt", "r")

for line in f:
    p = re.match(r'.+?((SAS|VM)[-a-zA-Z0-9 ]+).+?', line)
    if p:
        print (p.groups()[0])

在正则表达式中,我可以使用 (pattern1|pattern2) 来匹配 pattern1 或 pattern2 但是在re.match中,括号是用来匹配模式的。

如何在 re.match() 函数中指定“任意匹配”?

【问题讨论】:

  • print(p.group(1))

标签: python regex match


【解决方案1】:

这是一种方法。

例如:

import re

with open(filename) as infile:
    for line in infile:
        line = re.sub(r"[^A-Za-z\-\s]", "", line.strip())
        if line.startswith(("VM", "SAS")):
            print(line)

输出:

VM - This is VM
SAS - This is SAS

【讨论】:

    【解决方案2】:

    试试这样:

    with open('1.txt') as f:
        for line in f:
            extract = re.match('.+?((SAS|VM)[-a-zA-Z0-9 ]+).+?', line)
            if extract:
                print(extract.group(1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 2015-10-24
      相关资源
      最近更新 更多