Amruta Amruta - 8 days ago 5
Python Question

How to avoid grouping in regex

Hello I am trying to parse a string like '2.2.2.2-22'
while using python re.findall function I am getting two groups:
I don't understand what is wrong with the RE:

re.findall(r"([\d.]+(-\d+)?)", "2.2.2.2-22")


This gives me result as: [('2.2.2.2-22', '-22')]
I do not want the second group. How can I fix this?

Answer

To avoid the grouping you can use ?:

>>> import re
>>> re.findall(r"([\d.]+(?:-\d+)?)",  "2.2.2.2-22")
['2.2.2.2-22']

It will force that group to exists, but it will not catch and return the value.