用于提取数字和字符串

时间:2017-02-17 10:53:10

标签: python regex string

我需要从字符串中提取一些数据,字符串就是这样的fixed-string-<number>-<string>Fixed string总是一样的,我需要取出数字及其字符串。

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

谢谢你。

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:1)

这也有效:

$('.text-block:first').html('example text');

https://ideone.com/4RRwff

答案 2 :(得分:1)

您正在使用re.match,它尝试匹配字符串开头(即第一个字符)的模式。 这里,“initial-string /”阻止它匹配。

您可以在模式中包含“initial-string /”,也可以使用re.search,它将匹配字符串中的任何位置。

请注意,使用原始字符串(r'my string with \ 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')
相关问题