0

I'm trying to match semantic versions with regex where the patch (or 3rd digit) is optional. I have most of this working, but the last, optional digits won't get matched in my group.

Example is at: https://regex101.com/r/ZuitFG/3

I'm trying to match the versions in:

Release 2.6 Now Live
Release 12.46.30 Now Live
Release 2.6.0 Now Live
Release 2.6.1 Now Live

with /Release (\d+\.\d+[\.\d]?)/ and it just matches x.x. and never includes the last set of digits. I've re-read the explanation of what this regex does several times and I'm not able to see what I'm doing incorrectly.

Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    `[\.\d]` means "a dot _or_ a single digit" - use `(?:\.\d+)?` which is an optional non-capturing group matching a dot followed by a digit _matched 1 to infinity times_. – h2ooooooo Nov 04 '17 at 21:35
  • `[...]` always matches a single character. – melpomene Nov 04 '17 at 21:36

1 Answers1

2

The [\.\d]? is an optional character class that matches either a . or a digit, 1 or 0 times.

That is why only a dot was matched if there was a . + digit(s) sequence after two sequences of digits and dots.

You must use a grouping construct. A non-capturing group seems the best here since it won't create any other subgroup:

Release (\d+\.\d+(?:\.\d+)?)
                 ^^^^^^^^^

See the regex demo.

The (?:\.\d+)? matches an optional (1 or 0 times) sequence of . and then 1+ digits.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563