1

我正在开发一个尝试一些正则表达式的函数。让我解释。

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))
    }
}

我有$Matches.NAME返回字符串"A_UserINTEL",如“A_UserINTELASUS""A_UserINTEL_Adobe"

我需要区分来自的 2 个字符串$Matches.NAME,因此需要编写几个测试。

  • "A_UserINTEL"并且"A_UserINTELASUS"必须返回"UserINTEL"

  • "A_UserINTEL_Adobe"必须返回"UserINTEL_Adobe"

Test1 允许我检索"UserINTEL",但我没有成功 test2 带给我"UserINTEL_Adobe"

任何想法?谢谢你。

4

1 回答 1

1

有一种方法,而不仅仅是一种方法,尤其是在正则表达式方面,但这里有一种方法:

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))
    }
}
于 2018-07-30T15:36:35.460 回答