Search code examples
javascriptregexrubyregex-group

Regex repeated pattern


I am tryting the match the following pattern:

((1.0 4) (2.0 5) .... (10.0 8))

The tuple (X N), where X is a floating point number with optional exponent and N is an integer, can be repeated several times.

I tried on this website and I could generate a regex for a fixed number of tuples. For example for 2 tuples I would get

^\(\(([+-]?(?=\.\d|\d)(?:\d+)?(?:\.?\d*))(?:[eE]([+-]?\d+))?\s[0-9]+\)\s\(([+-]?(?=\.\d|\d)(?:\d+)?(?:\.?\d*))(?:[eE]([+-]?\d+))?\s[0-9]+\)\)$

How can I modify the pattern so that the number of tuples is arbitrary? I think I will have to use some kind of grouping, but regex is quite new for me.


Solution

  • You may use the following pattern:

    ^\(\(\d+(?:\.\d+)? \d+\)(?:\s*\(\d+(?:\.\d+)? \d+\))*\)$
    

    Demo

    This pattern matches:

    ^
    \(                             (
    \(\d+(?:\.\d+)? \d+\)          a leading tuple
    (?:\s*\(\d+(?:\.\d+)? \d+\))*  space, more tuples
    \)                             )
    $