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).
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.
@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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With