python正则表达式将字符和数字匹配在一起

时间:2013-12-05 08:35:28

标签: python regex

我需要一个模式来匹配数字之间的字符,我应该将什么定义为匹配字符和数字的模式?

示例字符串(粗体字符串是我应该匹配的):

IP / 51-0000523b ivr s 2 Up BackGround 5230f668473bd / MainIVR 4566658 00:00:22`(无)

IP / 51-0000523b ivr s 2 Up BackGround dh234926b9900 / MainIVR 4566658 00:00:22`(无)

IP / 51-0000523b ivr s 2 Up BackGround l23423y98t232 / MainIVR 4566658 00:00:22`(无)

IP / 51-0000523b ivr s 2 Up BackGround 5230f668473bd / MainIVR 4566658 00:00:22`(无)

3 个答案:

答案 0 :(得分:1)

数字之间的字符将是(?<=\d)[a-zA-Z]+(?=\d)(即只有那些直接被数字包含的字符,因此对于abc234def678hij它将是def),但是我觉得你的意思是人物和数字在一起;那将[a-zA-Z0-9]+简单明了。

答案 1 :(得分:0)

如果你想要的是看你的一个字符串是否包含在你的其他字符串中,这很简单。

import re

strsToTest = ["5230f668473bd","dh234926b9900","l23423y98t232","ju9898qr9898g"]
containedIn = "IP/51-0000523b ivr s 2 Up BackGround 5230f668473bd/MainIVR 4566658 00:00:2"
strsMatched = []
for s in strsToTest:
    if(re.search(s, containedIn)) :
    strsMatched.append(s)
print strsMatched

可能刚刚

strsToTest = ["5230f668473bd","dh234926b9900","l23423y98t232","ju9898qr9898g"]
containedIn = "IP/51-0000523b ivr s 2 Up BackGround 5230f668473bd/MainIVR 4566658 00:00:2"
strsMatched = []
for s in strsToTest:
    if(s in containedIn) strsMatched.append(s)
printStrsMatched

如果你想要做的是提取粗体字符串,那么

import re

strs = ["IP/51-0000523b ivr s 2 Up BackGround 5230f668473bd/MainIVR 4566658 00:00:22`", "IP/51-0000523b ivr s 2 Up BackGround dh234926b9900/MainIVR 4566658 00:00:22`"]#etc
results = []
for s in strs:
    m = re.match(".*BackGround\s(\w+)/.*",s)
    results.append(m.groups(1));
print(results)

答案 2 :(得分:0)

让我们说given_string包含整个字符串

all_numbers = re.findall(' (\S+)/Main', str)

简单!