Python正则表达式使用findall获得所有匹配项

时间:2018-11-08 16:43:45

标签: python regex

假设我有这个字符串:

string = 'start asf[2]+asdfsa[0]+fsad[1]'

我想将上面的整数按照它们在字符串中出现的顺序提取到数组中:

[2, 0, 1]

我已经尝试过findall,但是它不起作用:

print re.findall(r'start .*\[(.)\]', string)

它输出:

['1']

我将如何实现?

2 个答案:

答案 0 :(得分:1)

这是一种方法

>>> regex = re.compile("(?<=\[)([0-9]){1}?(?=\])")
>>> string = 'start asf[2]+asdfsa[0]+fsad[1]'
>>> re.findall(regex, string)
['2', '0', '1']

演示

>>> import re
>>> def get_all_integers_between_square_brackets(*, regex, string):
...     return map(int, re.findall(regex, string))
...
>>> regex = re.compile("(?<=\[)([0-9]){1}?(?=\])")
>>> integers = get_all_integers_between_square_brackets(
                               regex=regex , 
                               string='start asf[2]+asdfsa[0]+fsad[1]'
                               )
>>> list(integers)
[2, 0, 1]

>>> integers = get_all_integers_between_square_brackets(
                          regex=regex, 
                          string='start asf[hello]+asdfsa[world]+fsad[1][2][]')
>>> list(integers)
[1, 2]

答案 1 :(得分:0)

对上述答案进行了小的更改。 上面的答案仅当是一个数字时才提取。

expression = re.compile("(?<=\[)([0-9]+)(?=\])")

这将返回[]内的所有数字

示例

string='start asf[123]+asdfsa[0]+fsad[1]
output = [123, 0, 1]

代码

>>>import re
>>>def fetch_digits(expression, string):
     ...return map(int, re.findall(expression, string))

>>>expression = re.compile("(?<=\[)([0-9]+)(?=\])")
>>>int_map = fetch_digits(expression,'start asf[123]+asdfsa[0]+fsad[1]')
>>>list(int_map)