Powershell 正则表达式获取字符串的一部分

Powershell Regex expression to get part of a string

我想将字符串的一部分用于其他地方。例如,我有以下字符串:

我想从字符串中获取值“XYZ 是项目名称”。数字前的“项目”和字符“-”将始终存在。

# define the input string
$str = 'Project XYZ is the project name - 20-12-11'

# use regex (-match) including the .*? regex pattern 
# this patterns means (.)any char, (*) any times, (?) maximum greed
# to capture (into brackets) the desired pattern substring
$str -match "(Project.*?is the project name)"

# show result (the first capturing group)
$matches[1]

我认为 lookaround 正则表达式在这里可以工作,因为“项目”和“-”始终存在:

(?<=Project ).+?(?= -)

环视对于处理获取子字符串的情况很有用。

解释:

  • (?<= = 负面回顾
  • Project = 起始字符串(包括space)
  • ) = 关闭负面回顾
  • .+? = 匹配介于两者之间的任何内容
  • (?= = 正面前瞻
  • - = 结束字符串
  • ) = 关闭正面前瞻

PowerShell 示例:

Function GetProjectName($InputString) {
    $regExResult = $InputString | Select-String -Pattern '(?<=Project ).+?(?= -)'
    $regExResult.Matches[0].Value
}

$projectName = GetProjectName -InputString "Project XYZ is the project name - 20-12-11"
Write-Host "Result = '$($projectName)'"

这是另一个正则表达式版本。 [grin] 它可能更容易理解,因为它使用了一些基本的正则表达式模式。

它的作用...

  • 定义输入字符串
  • 定义要匹配的前缀
    这将只保留之后的内容。
  • 定义要匹配的后缀
    这部分将只保留之前的内容。
  • 触发替换
    () 中的部分是将放入第一个捕获组的部分。
  • 显示保留的内容

代码...

$InString = 'Project XYZ is the project name - 20-12-11'
# "^" = start of string
$Prefix = '^project '
# ".+' = one or more of any character
# "$" = end of string
$Suffix = ' - .+$'

# "" holds the content of the 1st [and only] capture group
$OutString = $InString -replace "$Prefix(.+)$Suffix", ''

$OutString