【问题标题】:Multiple Regular expression in one line一行中的多个正则表达式
【发布时间】:2020-02-12 23:38:20
【问题描述】:
list_num=['AYSGS11458630001111252','1234567','LUPUP003164311E0111644','ABCGFD','AFC123A']

对于上面的 list_num,我想写 RE,它给出如下。

预期输出

AYSGS11458630001111252
none
LUPUP003164311E0111644
none
none

输出应该是列表中的两个项目

我在网上写过,请指正并建议我。

re.match((r"^(([A-Z]{5}[0-9]{17})|([A-Z]{5}[0-9]{9}[A-Z]{1}[0-9]{7}))$", list_num)

【问题讨论】:

  • 对于上面的 list_num,我想写 RE 来获取它们。 获取两者什么?你有什么问题?
  • 你不能只展示一些看似随机的字符串的两个例子,然后期望人们给你完美的答案。您将需要解释这两个字符串是如何产生的以及它们的用途。您需要提供一些上下文。否则,r'(.*)^ 之类的内容将是您问题的完美答案。查看stackoverflow.com/help/how-to-ask
  • @AMC 我已经纠正了我的问题
  • 你能不能用文字描述一下,你想匹配什么样的模式?
  • 一个选项 5 个大写字母和 17 个数字。第二个选项 5 个大写字母和 9 个数字和 1 个大写字母和 7 个数字。如果其中一个匹配,我也想显示该序列号@user8408080

标签: python regex data-science data-analysis


【解决方案1】:

re.match(pattern, string, flags=0) 被定义为return re.compile(pattern, flags).match(string) 它不能处理一个列表 字符串而不是字符串,但这很容易用循环修复。 但是由于我们要多次运行同一个表达式, 最好编译一次,而不是在循环中重复。

这就是我要做的:

import re
list_num=['AYSGS11458630001111252','1234567','LUPUP003164311E0111644','ABCGFD','AFC123A']

pattern = r"^(([A-Z]{5}[0-9]{17})|([A-Z]{5}[0-9]{9}[A-Z]{1}[0-9]{7}))$"
compiled_pattern = re.compile(pattern)

for m in map(compiled_pattern.match, list_num):
    #you could also use pattern.fullmatch, and not enclose your pattern with ^ and $
    if m is not None:
        print(m.string)
    else:
        print(m)
## shows:
##AYSGS11458630001111252
##None
##LUPUP003164311E0111644
##None
##None

否则:

x = [m.string if isinstance(m, re.Match) else m
     for m in map(compiled_pattern.match, list_num)]
print (x)
#['AYSGS11458630001111252', None, 'LUPUP003164311E0111644', None, None]

'or even this:'
def multi_match(pattern, seq):
    compiled_pattern=re.compile(pattern)
    return [m.string if isinstance(m, re.Match) else m
            for m in map(compiled_pattern.match, list_num)]

print(multi_match(pattern, list_num))
#['AYSGS11458630001111252', None, 'LUPUP003164311E0111644', None, None]

或者如果不需要保留索引位置,例如:

def filter_match(pattern, seq):
    compiled_pattern=re.compile(pattern)
    return list(filter(
        lambda line: compiled_pattern.match(line) is not None,
        list_num))

print(filter_match(pattern, list_num))
#['AYSGS11458630001111252', 'LUPUP003164311E0111644']

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多