【问题标题】:Parse only second part using Python and re仅使用 Python 解析第二部分并重新
【发布时间】:2017-05-20 05:07:59
【问题描述】:

我有数据:

audio_9813314_456239162
audio_9813314_456239175
audio_9813314_456239145
audio_9813314_456239178

我只需要数字的第二部分,比如

456239162
456239175

【问题讨论】:

    标签: python regex parsing


    【解决方案1】:

    如您所见,我循环遍历数据并将数据拆分到 _ 和最后一部分 [-1]

    data = ["audio_9813314_456239162",
    "audio_9813314_456239175",
    "audio_9813314_456239145",
    "audio_9813314_456239178"]
    
    new_data = []
    for i in data:
      last_part = i.split("_")[-1]
      new_data.append(last_part)
    
    print(new_data)
    

    输出:

    ['456239162', '456239175', '456239145', '456239178']
    output:
    

    【讨论】:

      【解决方案2】:

      您在这里有几个选项,因此您可以选择其中一个。您可以通过以下两种方式获得它。

      1. 一个简单的findall

      如果你知道你需要的数字总是在末尾或第二个位置,你可以使用findall

      import re
      str1 = 'audio_9813314_456239162'
      
      print re.findall('(\d+)', str1)[-1]
      print re.findall('(\d+)', str1)[1]
      

      输出

      456239162
      456239162
      
      1. 使用match 明确搜索术语

      匹配从第一个字符开始,从左到右,因此您需要考虑到您要查找的数字之前的所有内容。注意:第 0 个索引是整个字符串,所以我们得到第 1 个索引。

      print re.match('.+_\d+_(\d+)', str1).group(1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 2023-02-01
        • 2018-10-31
        • 1970-01-01
        相关资源
        最近更新 更多