简体   繁体   中英

Extract a particular number followed by a command line argument variable from a string in python

Firstly am saying this is not this : How to get integer values from a string in look here ..ok so

my question is : mv = /dev/vg10/lv10:cp:99 i need to extract vg10 's "10" not [10]. mv is a string

my final output should be only 10 that should extracted from vg

my python version: Python 2.6.1

Thanks in advance.. please help me :(

You should look into the regular expressions module of python. Simply "import re" in your script to provide regex capabilities. By the way if you only want the numbers following the string "vg" then the following script should do the trick.

import re
urString = "/dev/vg10/lv10:cp:99"
Matches = re.findall("vg[0-9]*", mv)
print Matches

Now matches will have a list containing all vg'number'. That [0-9]* means any digit any number of times. Parse it again to get the numbers from it. You should read more about regular expressions. It's fun.

Extending the answer to match OP's requirement:

In [445]: Matches
Out[445]: ['vg10']

In [446]: int(*re.findall(r'[0-9]+', Matches[0]))
Out[446]: 10

Are you talking about this:

import re
mv = "/dev/vg10/lv10:cp:99"
print re.search('/dev/vg(\d+)', mv).groups()

Or if vg can be something else, but it is always the second item you want you can do this:

print re.search('/dev/\w+(\d+)/lv10:cp:99', mv).groups()
import re

mv =  '/dev/mapper/vg8-lv8-eSPAN_MAX_d4:eSPAN_MAX_d4:99'

print re.findall(r'(?<=vg)\d*', mv)

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