Solution for Regex C# – optional group in the middle
is Given Below:
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.
How it should be changed to capture desired values?
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.
You can use
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.
I hope I understand your goals and this should work:
.*?.– loosely capture everything leading up to the first period
([d.]+)– capture the remaining digits and periods into capture group #1