Reputation: 173
import os,re
def test():
list = re.findall(r'(255\.){2}','255.255.252.255.255.12')
print list
if __name__ == '__main__':
test()
the output :“['255.', '255.']”
why not 【255.255,255.255】 ?
the mactch object should is "255.255"
How can i get the correct output result?
Upvotes: 2
Views: 125
Reputation: 870
Mm, not quite. First off, you'll want a non-capturing group - the capturing group you have there will only capture '255.', and use that as the output for re.findall
.
Example:
re.findall(r'(?:255\.){2}', '255.255.252.255.255.12')
The (?:) construct is a non-capturing group - and without any capturing groups, re.findall returns the entire matching string.
Note that this won't actually return ['255.255', '255.255']
- it will actually return ['255.255.', '255.255.']
.
Upvotes: 1
Reputation: 298146
In your regex, you're only capturing the first 255.
. You need to wrap everything you want to capture in a capturing group:
>>> re.findall(r'((?:255\.){2})','255.255.252.255.255.12')
['255.255.', '255.255.']
(?:...)
is a non-capturing group. It basically lets you group things without having them show up as a captured group.
Upvotes: 2