简体   繁体   中英

Extract a substring from a string based on the position of character - Python

Im trying to extract the substrings from the below string

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

as string 1 : versionCode='1' and as string 2: versionName='1.0'

I used str.find('versionCode) which returns me the index of 'v' in the versioncode and i used string length to access '1'. However there are time the versioncode might be a double digit number so I can't fix the location of the digit. Is there a way to achieve this?

If the string is

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

I need to extract 12 and 12.0. My implementation can support single digits but the digits will vary.

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

You'll need to use regular expressions to do this.

In each of the below lines we use the pattern (.*?) to perform a non-greedy search within the quotes to extract the string, and then pull group(1) rather than group(0) on the returned object, as 0 returns the full match across the whole input string, and 1 gives the first regex capture group.

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 

And this outputs:

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

You could manipulate the string with built-in methods to get the values you need:

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()

Or you could build a dictionary:

>>> 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

Or if you don't care about stripping the "'"s

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM