【问题标题】:Extract a substring from a string based on the position of character - Python根据字符的位置从字符串中提取子字符串 - Python
【发布时间】:2013-09-17 23:49:23
【问题描述】:

我试图从下面的字符串中提取子字符串

   package: name='com.example.tracker' versionCode='1' versionName='1.0'

作为字符串 1:versionCode='1' 并作为字符串 2:versionName='1.0'

我使用 str.find('versionCode) 返回版本代码中“v”的索引,并使用字符串长度访问“1”。但是有时版本代码可能是两位数,所以我无法修复数字的位置。有没有办法做到这一点?

如果字符串是

    package: name='com.example.tracker' versionCode='12' versionName='12.0'

我需要提取 12 和 12.0。 我的实现可以支持单个数字,但数字会有所不同。

 if line.find('versionCode') != -1:
            x = line.find('versionCode') 
            versionCode = line[x+13:x+15] 

【问题讨论】:

  • 使用正则表达式来做到这一点,或者编写一个真正的解析器。

标签: python string substring


【解决方案1】:

您需要使用regular expressions 来执行此操作。

在下面的每一行中,我们使用模式(.*?) 在引号内执行非贪婪搜索以提取字符串,然后在返回的对象上拉动group(1) 而不是group(0),如@987654325 @ 返回整个输入字符串的完全匹配,1 给出第一个正则表达式捕获组。

import re

packageDetails = "package: name='com.example.tracker' versionCode='1' versionName='1.0'"
name = re.search("name='(.*?)'", packageDetails).group(1)
versionCode = re.search("versionCode='(.*?)'", packageDetails).group(1)
versionName = re.search("versionName='(.*?)'", packageDetails).group(1)

print "package name is :", name
print "version code is :", versionCode
print "version name is :", versionName 

这个输出:

package name is : com.example.tracker
version code is : 1
version name is : 1.0

【讨论】:

    【解决方案2】:

    您可以使用内置方法操作字符串以获得所需的值:

    packageDetails = "package: name='com.example.tracker' versionCode='1' versionName='1.0'"
    details = packageDetails
    params = ['name=', 'versionCode=', 'versionName=']
    params.reverse()
    values = []
    for p in params:
        details, v = details.split(p)
        values.append(v.strip().strip("'"))
    values.reverse()
    

    【讨论】:

      【解决方案3】:

      或者你可以建立一个字典:

      >>> details = { x.split('=')[0] : x.split('=')[1].strip("'") for x in a.split()[1:] }
      >>> details
      {
        "name" : "com.example.tracker",
        "versionCode" : "1",
        "versionName" : "1.0"
      }
      >>> details['name']
      "com.example.tracker"
      >>> details['versionCode'] == '1'
      true
      

      或者如果你不关心剥离“'”s

      >>> dict(x.split('=') for x in a.split()[1:])
      {
        "name" : "'com.example.tracker'",
        "versionCode" : "'1'",
        "versionName" : "'1.0'"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-07
        • 2016-06-01
        • 2015-10-05
        • 2011-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多