简体   繁体   English

从python中的字符串中提取特定数字,然后是命令行参数变量

[英]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 首先我说这是不是这样的:如何从一个字符串中获得整数值这里看看 ..ok所以

my question is : mv = /dev/vg10/lv10:cp:99 i need to extract vg10 's "10" not [10]. 我的问题是: mv = / dev / vg10 / lv10:cp:99我需要提取vg10的“ 10”而不是[10]。 mv is a string mv是一个字符串

my final output should be only 10 that should extracted from vg 我的最终输出应该只有10,应该从vg中提取

my python version: Python 2.6.1 我的python版本: Python 2.6.1

Thanks in advance.. please help me :( 在此先感谢..请帮助我:(

You should look into the regular expressions module of python. 您应该查看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. 顺便说一句,如果您只希望字符串“ vg”后面的数字,那么以下脚本应该可以解决问题。

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'. 现在,比赛将有一个包含所有vg'number'的列表。 That [0-9]* means any digit any number of times. [0-9] *表示任意位数任意次数。 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: 扩展答案以符合OP的要求:

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: 或者,如果vg可以是其他东西,但它始终是您希望执行的第二项操作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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