Dandan
Dandan

Reputation: 529

Simple regex with dot separator

I'm trying to extract two strings from one of two formats with two groups as a result. The formats are:

val1.val2 - group1 should be "val1" and group2 should be "val2"

val2 - group1 should be "" and group2 should be "val2"

Closest I came up with is this:

([^\.]*?)\.?(.+)

But the lazy operator on the first group basically makes the second group capture the entire string when there's a "." in it.

Upvotes: 1

Views: 858

Answers (1)

Jerry Jeremiah
Jerry Jeremiah

Reputation: 9618

I am pretty sure this works:

(?:([^.]*)\.)?(.+)

It has:

  • an optional non-capturing group that contains:
    • group 1: text before a literal dot
    • a literal dot
  • group 2: any amount of text

If the dot is missing the optional non-capturing group won't exist (and neither will group 1 which is inside) so all the text will go into group 2. If the dot does exist then group 1 and group 2 are both filled.

Thanks to @Dandan for the improvement

Upvotes: 1

Related Questions