Python re.findall prints all templates

>>> match = re.findall('a.*?a', 'a 1 a 2 a 3 a 4 a') >>> match ['a 1 a', 'a 3 a'] 

How do I print it?

 ['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a'] 

Thanks!

+6
source share
3 answers

I think using a positive outlook forecast should do the trick:

 >>> re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a') ['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a'] 

re.findall returns all groups in a regular expression - including in standby mode. This works because the forward-looking statement does not use any of the lines.

+6
source

You can use an alternative regex module that allows matching matches:

 >>> regex.findall('a.*?a', 'a 1 a 2 a 3 a 4 a', overlapped = True) ['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a'] 
+5
source
 r = re.compile('a.*?a') # as we use it multiple times matches = [r.match(s[i:]) for i in range(len(s))] # all matches, if found or not matches = [m.group(0) for m in matches if m] # matching string if match is not None print matches 

gives

 ['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a'] 

I don’t know if this is the best solution, but here I check every substring that goes to the end of the line to match the given pattern.

+4
source

Source: https://habr.com/ru/post/948697/


All Articles