WoJ
WoJ

Reputation: 30072

How to optionally match a group?

I have two possible patterns:

1.2 hello
1.2.3 hello

I would like to match 1, 2 and 3 if the latter exists.

Optional items seem to be the way to go, but my pattern (\d)\.(\d)?(\.(\d)).hello matches only 1.2.3 hello (almost perfectly: I get four groups but the first, second and fourth contain what I want) - the first test sting is not matched at all.

What would be the right match pattern?

Upvotes: 1

Views: 39

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Your pattern contains (\d)\.(\d)?(\.(\d)) part that matches a digit, then a ., then an optional digit (it may be 1 or 0) and then a . + a digit. Thus, it can match 1..2 hello, but not 1.2 hello.

You may make the third group non-capturing and make it optional:

(\d)\.(\d)(?:\.(\d))?\s*hello
          ^^^      ^^

See the regex demo

If your regex engine does not allow non-capturing groups, use a capturing one, just you will have to grab the value from Group 4:

(\d)\.(\d)(\.(\d))?\s*hello

See this regex.

Note that I replaced . before hello with \s* to match zero or more whitespaces.

Note also that if you need to match these numbers at the start of a line, you might consider pre-pending the pattern with ^ (and depending on your regex engine/tool, the m modifier).

Upvotes: 1

Related Questions