2
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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.'].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.