2017-02-17 128 views
-1

我需要从字符串中提取一些数据,字符串是这样的fixed-string-<number>-<string>Fixed string总是相同的,我需要提取数字和它的字符串。正则表达式提取数字和字符串

在蟒蛇3.5,我使用的是接下来的正则表达式

str = 'initial-string/fixed-string-124-jeff-thompson' 
result = re.match('fixed-string-([0-9]*)-(.*)', str) 
print (result) 

但结果总是None值,我查了字符串,并将其井形成。

我在做什么错?

更新

testing = 'first-string/fixed-string-123-jeff-thompson' 
pattern = r'fixed-string-(\d+)-(.*)' 

result = re.match(pattern, testing) 

我进行了测试,代码仍然返回我None

谢谢你。

+4

不要使用'str'作为变量名。你的正则表达式确实有效,参见[这个示例](https://ideone.com/g4r2yC)。请注意,'re.match'只在字符串start处寻找匹配项。 –

+0

请提供您希望工作的试用字符串。 – kazemakase

回答

1

您正在使用re.match,它试图从开头处匹配的模式(即从第一个字符开始)。 在这里,“初始字符串/”阻止匹配。

你可以在你的模式中包含“initial-string /”,或者使用re.search将匹配从你的字符串中的任何位置开始。

请注意,最好使用原始字符串(r'my字符串与\ backslahes')以避免潜在的需要在模式中转义。

string = 'initial-string/fixed-string-124-jeff-thompson' 
result = re.search(r'fixed-string-([0-9]*)-(.*)', str) 
result.groups() 
# ('124', 'jeff-thompson') 

result = re.match(r'initial-string/fixed-string-([0-9]*)-(.*)', str) 
result.groups() 
# ('124', 'jeff-thompson') 
2

以下工作:

> s = 'fixed-string-345-abc' 
> re.match(r'fixed-string-(\d+)-(.+)') # if num and string shouldn't be empty 
# re.match(r'fixed-string-(\d*)-(.*)') 
> m.group(1, 2) 
('345', 'abc') 
+0

在Python 3.x中,速记类是可识别Unicode的。 '\ d'比'[0-9]'多。基本上,它是相同的正则表达式OP使用,虽然少一点精确。 –

+0

这段代码适用于python控制台,但不适用于我的代码。 're.match'仍然返回给我'没有'。 –

1

这工作,也:

import re 
s = 'fixed-string-123-456' 
result = re.findall('(?<=fixed-string-)(\d+)-(.*)', s) 
if result: 
    print (result[0]) 
#('123', '456') 

https://ideone.com/4RRwff