Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Regex - optional named group matches

Let's say I have a string:

$string1 = "Hello_World:How, are, you:-all -is -well"

I would like to use a regex to match the sections of the string seperated by colon's into named groups. For example:

$pattern = "(?<first>.*)\:(?<second>.*)\:(?<third>.*)"

This $pattern would match $string1 successfully and I would end up with the following matches:

first=Hello_World
second=How, are, you
third=-all -is -well

This is good, but there is a problem. The $string1 could potentially be missing the third section, for example:

$string1 = "Hello_World:How, are, you"

Unfortunately, this $string1 no longer matches the regex pattern. How do I make it so that the pattern will match both formats of string? (i.e. I should always have a "first" and "second" match, and only a "third" match if it's provided).

like image 328
DaveUK Avatar asked Dec 20 '11 23:12

DaveUK


2 Answers

Use the ? quantifier and a non capturing group. Also, don't use .*!

(?<first>[^:]*):(?<second>[^:]*)(?::(?<third>.*))?

Also, you should anchor your regex at least at the beginning.

like image 195
fge Avatar answered Sep 21 '22 05:09

fge


@fge's answer should work, but if this is all you are doing, I would recommend that you use String.Split to get what you need:

$split = $string1.split(':')
if(($split.count -eq 2) -or ($split.count -eq 3)){
    #use $split[0] etc.
}
like image 30
manojlds Avatar answered Sep 17 '22 05:09

manojlds