Search code examples
pythonregexregex-group

Regex statement that matches an optional character into the same group


Regex sandbox:

https://regex101.com/r/nAhuot/1

I need to group floats with ints. The keyword here is the same group. I can match beyond the decimal point like so:

(\d+)?(.)?(\d+)[ \t]+NUM(\d) <--- Regex to match beyond the decimal
(\d+)[ \t]+NUM(\d) <---- Regex to match up to the decimal

This is the text:

1.5707963267949         NUM0 ;
0                       NUM1 ;
0                       NUM2 ;
0                       NUM3 ;
0                       NUM4 ;
0                       NUM5 ;

The expected result is to have 2 groups within the regex, look like this:

(1.5707963267949,NUM0),(0,NUM1),(0,NUM2),(0,NUM3),(0,NUM4),(0,NUM5)

My solution makes multiple groups, how can I make it to group into only one group?


Solution

  • Unsure why the answer was wiped from the comments, but this is what worked:

    ((?:\-)?\d+(?:\.\d+)?)[ \t]+NUM(\d+)
    

    Thank you to the user who solved it, lost his username