Amruta Amruta - 1 year ago 98
Python Question

How to avoid grouping in regex

Hello I am trying to parse a string like ''
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+)?)", "")

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

Answer Source

To avoid the grouping you can use ?:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download