2

Here is a piece of text I have :

G1   13.00
G1    3.00
      0.00
       27C

I am trying to use regex to capture one group which is a alpha-numeric code (G1 or 27C) or another group which is a float (xx.xx), or both of them.

For this example, I want this specific return:

(G1,13.00)
(G1,3.00)
(,0.00)
(27C,)

this is the closest solution I have :

\(?:(\w+) +(\d+\.\d+))|(?: +(\d+\.\d+))|(?: +(\w+))\

The problem with this solution is that the last 2 rows values are captured in the 3rd and a 4th group:

(G1,13.00,,)
(G1,3.00,,)
(,,0.00,)
(,,,27C)

Any ideas on how to solve it ?

I have found this question which is close : In a regular expression, match one thing or another, or both but it answers how to match and not to capture.

jscs
  • 63,694
  • 13
  • 151
  • 195
GregOizo
  • 43
  • 4

1 Answers1

1

You just need same patterns to be matched by same capturing groups.

This will return always 2 groups:

(\w+)? *\b(\d+\.\d+)?

See demo

EDIT: if you want no empty match, try this:

(?=\w)(\w+(?=$|\s))? *\b(\d+\.\d+)?

See demo

logi-kal
  • 7,107
  • 6
  • 31
  • 43