Regular expression matching in PowerShell

后端 未结 5 844
野性不改
野性不改 2021-01-01 13:41

Is there an elegant one-liner for doing the following?

$myMatch = \"^abc(.*)\"
$foo -match $myMatch
$myVar = $matches[1]

I\'m interested in

5条回答
  •  感动是毒
    2021-01-01 14:01

    I am not sure about the elegance, but here is something useful:

    PS > "123.134" -match "(?[0-9]{3})\.(?[0-9]{3})"
    True
    PS > $Matches
    
    Name                           Value
    ----                           -----
    P2                             134
    P1                             123
    0                              123.134
    
    
    PS > $Matches["P1"]
    123
    

    ? gives the label P1 to the first capture. It helps to understand.

    PS > ([regex]("(?[0-9]{3})\.(?[0-9]{3})")).matches("123.123")[0].groups["P1"].value
    123
    

    In your case:

    PS > $foo = "123.143"
    PS > ([regex]("(?[0-9]{3})\.(?[0-9]{3})")).matches($foo)[0].groups["P1"].value
    123
    PS > ([regex]("(?[0-9]{3})\.(?[0-9]{3})")).matches($foo)[0].groups["P2"].value
    143
    

提交回复
热议问题