【问题标题】:Find a string with certain propoerty in Python在 Python 中查找具有特定属性的字符串
【发布时间】:2021-11-12 09:44:50
【问题描述】:

假设我有字符串:abcNumber:"1234"ID:XXXYYY END。我现在如何检查这个字符串是否包含短语ID:...YYY,其中... 表示ID 和YYY 之间可以通过任何方式(带有3 个符号)?我想得到答案:True of False。

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

您可以使用re 模块进行正则表达式搜索。

import re

s = 'abcNumber:"1234"ID:XXXYYY END'

pat = re.compile(r'''
  ID     # a literal ID
  .{3}   # any three characters
  YYY    # a literal YYY''', re.X)
if re.search(pat, s):
    print("Yep!")

【讨论】:

    【解决方案2】:

    正则表达式的典型用例:

    import re
    
    s = 'abcNumber:"1234"ID:XXXYYY END'
    
    match = re.search(r"ID:(.{3})YYY", s)  # capture the group of 3 anthings between your markers
    if match:
        print(f"found: {match.group(1)}")
    
    # found: XXX
    

    【讨论】:

    • 谢谢!如果字符串是abcNumber:"1234"ID:XXXYYY; NEXT ID:ZZZAAA; 并且我想获取所有ID,即XXXYYY, ZZZAAA 形式的XXXYYY 和ZZZAAA,该怎么办?
    猜你喜欢
    • 2014-07-28
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2012-05-09
    • 2020-12-15
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多