【问题标题】:I need a way to find all instances of a string and then get everything from the end of that string to another string我需要一种方法来查找字符串的所有实例,然后获取从该字符串末尾到另一个字符串的所有内容
【发布时间】:2020-11-24 16:51:32
【问题描述】:

我需要一种方法来查找字符串的所有实例,然后获取从该字符串末尾到另一个字符串的所有内容。

我想要的一个例子:

string = '''
<country:England> abcdafsasffasfafasasasffsafdafuiugiugigoog
af <country:Spain> asfasfigfasgyafsguiosfbsafbuiasfuis
faiufsabasfbuiasfbfas <country: Italy>asfasfhasfhgasfgasiafs'''

对于单词国家的所有实例,我想在之后获取国家/地区的名称

Output = [England, Spain, Italy]

【问题讨论】:

    标签: python string substring


    【解决方案1】:

    regex findall 可以为您做到这一点。下面将捕获所有单词字符组 (\w+),模式以字符串 "country:" 开头,后跟一个可选空格,并以 ">"

    结尾
    import re
    
    output=re.findall(r"country: ?(\w+)>",string)
    

    print(output) 结果:

    ['England', 'Spain', 'Italy']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多