在 powershell 中丢弃字符串中的 ID

在 powershell 中丢弃字符串中的 ID

我有以下字符串类型的变量:

[string]$name = "juan maria alonso 78899229N"

我怎样才能只得到胡安玛丽亚阿隆索并丢弃数字和字母,用正则表达式总是有 8 个数字和一个字母?

结果:

[string]$name = "juan maria alonso"

我尝试这个:

 $result = where-object {$name -notmatch '[0-9][a-zA-Z]'};
 echo $name 

但我收到的是空的

答案1

请尝试以下操作:

$result = $name -replace '\s\d+[A-Za-z]',''
$result

答案2

以下代码将满足您的要求。我擅自添加了名称集合功能,因为您可能有多个名称,否则您只需手动编辑名称即可。

该代码确实假定 ID 代码始终位于字符串的末尾。

# create collection
$names = ("juan maria alonso 78899229N", "testing 12345678A", "and some more 12345678A")

# iterate through collection
$names | foreach-object {
    # create new variable with the name in this loop and convert to string.
    $name_from = $_.ToString()

    # Get the name by removing the last 10 chars (a space and id code)
    $name = $name_from.Substring(0,$name_from.Length - 10)

    #print $name for reference.
    $name
}

答案3

此选项

Clear-Host
[regex]::Matches("juan maria alonso 78899229N",'\b[^\d\W]+\b').Value -join ' '

# or this

Clear-Host
"juan maria alonso 78899229N" -replace '\d+[a-zA-Z]'

# Results
<#
juan maria alonso
#>

答案4

只是为了好玩,还有另一种选择:

PS keith> [string]$name = 'juan maria alonso 78899229N'
PS keith> $result = $name -replace '\s\w+$' ### '<space><one or more word characters><end-of-string anchor>
PS keith> $result
juan maria alonso
PS keith> $matches

Name                           Value
----                           -----
0                               78899229N

相关内容