Conditional If with REGEX

1.5k Views Asked by At

I'm working on a function to try some regex. Let me explain.

function traitement
{
    if ($Matches.NAME -match "^A_(?<test1>[\w{1,6}]{1,7})")
    {
        [void]($memberOfCollection.add($Matches.test1))
    }
    elseif ($Matches.NAME -match "^A_(?<test2>[]*)")
    {
         [void]($memberOfCollection.add($Matches.test2))
    }
    else
    {
        [void]($memberOfCollection.add($Matches.NAME))
    }
}

I have $Matches.NAME return string like "A_UserINTEL", "A_UserINTELASUS" or "A_UserINTEL_Adobe"

I need to differentiate 2 strings coming from $Matches.NAME and therefore write several tests.

  • "A_UserINTEL" and "A_UserINTELASUS" must return "UserINTEL".

  • "A_UserINTEL_Adobe" must return "UserINTEL_Adobe"

Test1 allows me to retrieve "UserINTEL" but I didn't succeed test2 to bring me "UserINTEL_Adobe".

Any idea? Thank you.

1

There are 1 best solutions below

0
On

There's a;ways more ways then just one, especially when it comes to regular expressions, but here's one way:

function traitement {
    # just for more clarity in the rest of the code
    $name = $Matches.NAME
    if ($name -match '^A_UserIntel(?:ASUS)?$') {
        # the regex tests for "A_UserINTEL" or "A_UserINTELASUS"
        [void]($memberOfCollection.add("UserINTEL"))
    }
    elseif ($name -match '^A_UserIntel_Adobe$') {
        # this elseif is basically the same as 
        # elseif ($name -eq 'A_UserIntel_Adobe') {
        # no real need for regex there..
        [void]($memberOfCollection.add("UserINTEL_Adobe"))
    }
    else {
        [void]($memberOfCollection.add($name))
    }
}