【问题标题】:How to output only the match string using Python?如何使用 Python 仅输出匹配字符串?
【发布时间】:2021-06-12 08:44:05
【问题描述】:

我想匹配一个字符串,然后打印匹配的字符串。

我需要从所有这些列表中匹配一个字符串mapping=C111。 这是我尝试过的。我可以找到匹配的字符串,但我不能只打印匹配的字符串。

import re
AllString = ["123A","B456","AGHF\C111\B321","3FEW/D654"]
print(type(AllString))
for str in AllString:
    mapping = "C111"
    findid = [re.match(mapping, str)]
    for f in findid:
       if f is not None:
           print(f)

输出是这样的:

<re.Match object; span=(0, 4), match='C111'>

我的期望结果是"AGHF\C111\B321"整个字符串。

请大家帮忙。非常感谢

【问题讨论】:

    标签: python string list output match


    【解决方案1】:
    import re
    AllString = ["123A","B456","C111\B321","3FEW/D654"]
    print(type(AllString))
    for str in AllString:
        mapping = "C111"
        findid = [re.match(mapping, str)]
        for f in findid:
           if f is not None:
               print(f.string) # output: C111\B321 and It makes sense
    

    或者:

    import re
    AllString = ["123A","B456","C111\B321","3FEW/D654"]
    print(type(AllString))
    for str in AllString:
        mapping = "C111"
        findid = [re.match(mapping, str)]
        for f in findid:
           if f is not None:
               print(mapping) # It meets your requirement but looks weird
    

    新更新:

    import re
    AllString = ["123A","B456","AGHF\C111\B321","3FEW/D654"]
    print(type(AllString))
    for str in AllString:
        mapping = r".+C111.+" # method 'match' should be used with regex
        findid = [re.match(mapping, str)]
        for f in findid:
           if f is not None:
               print(f.string)
    

    【讨论】:

    • 嗨@Gcode。我尝试了您的第一个答案,它仅在我有 "C111\B321" 时才有效,但我的更新案例是“AGHF\C111\B321”,但它不起作用。如果中间的目标字符串像"AGHF\C111\B321",则它不起作用。请你帮助我好吗。谢谢
    • 我把它改成了findid = [re.search(mapping, str)] 它可以工作。谢谢你。您可以编辑您的答案
    【解决方案2】:

    代码的一个问题是re.match 必须在字符串的开头匹配。您可以改用re.search,但在这种情况下不需要正则表达式。使用in:

    strings = ['123A','B456','AGHF\C111\B321','3FEW/D654']
    for s in strings:
        if 'C111' in s:
            print(s)
    
    AGHF\C111\B321
    

    如果您需要匹配 精确 字母数字序列且其周围没有多余的字母/数字,则使用 re.search\b(分词):

    import re
    
    strings = ["123A","B456","C111\B321","3FEW/ABC111DEF/D654","ABC\C111/DEF"]
    
    for s in strings:
        if re.search(r'\bC111\b',s):
            print(s)
    
    C111\B321
    ABC\C111/DEF
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 2017-03-21
      • 2011-03-22
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多