flowerpower
flowerpower

Reputation: 1

Regex C# - optional group in the middle

I have such source text with an optional group in the middle:

GH22-O0-TFS-SFSD 00-1-006.19135
GH22-O0-TFS-SFSD 00-1-006.1.19135

Desired value in the first case will be '19135' and in the second '1.19135'.

Regex has to match the whole string and select all characters after first "." - which is my Group 1. I tried to make subgroups and mark Group 3 as optional but it is not working.

Regex:

.*\.0*(([0-9])(\.0*([0-9]+)))

How it should be changed to capture desired values?

Upvotes: 0

Views: 404

Answers (3)

Serenus
Serenus

Reputation: 56

This should work for you:

.*?\.(.*)

This will match the whole string and include everything after the first period in capture group 1 regardless of character type.

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20737

I hope I understand your goals and this should work:

.*?\.([\d.]+)
  • .*?\. - loosely capture everything leading up to the first period
  • ([\d.]+) - capture the remaining digits and periods into capture group #1

https://regex101.com/r/0t9Ijy/1

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

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

See the regex demo. Details:

  • ^ - start of string
  • (.*?) - Group 1: any zero or more chars other than an LF char as few as possoble (as *? is a lazy quantifier)
  • \. - a dot
  • 0* - zero or more zeros
  • (\d+) - Group 2: any one or more digits
  • (?:\.0*(\d+))? - an optional occurrence of ., zero or more zeros, then Group 3 capturing one or more digits
  • $ - end of string.

Upvotes: 0

Related Questions