【问题标题】:unable to parse regex pattern form file to the variable in powershell无法将正则表达式模式表单文件解析为 powershell 中的变量
【发布时间】:2021-11-05 20:05:53
【问题描述】:

我正在寻找文件夹名称是否符合以下 powershell 中的正则表达式模式。

  1. 检查前 4 个字母是 HOST。
  2. 根据 c:\shortnameslist.csv 中的短名称检查接下来的 3 或 4 个字母。
  3. 检查最后三个字母是否为 END。

#$shortname = (Import-Csv "c:\shortnameslist.csv")

$foldername = "文件夹名称"

$regex = '\b^(HOST)($shortname)(END)\b'

$文件夹名-匹配$正则表达式

问题:

如何从正则表达式模式的 csv 列表中解析中间部分“短名称”。 谢谢。

【问题讨论】:

  • 看来您只需要将第一列中的所有值抓取到列表/数组中,然后加入| 并使用$regex = '^HOST(?:$shortname)END$'。注意 -match 不区分大小写。使用-cmatch 进行区分大小写的匹配。
  • @WiktorStribiżew 您需要在正则表达式两边加上双引号,否则变量 $shortname 将不会展开
  • @Theo 是的,很抱歉在复制/粘贴时没有注意到。

标签: regex powershell shell scripting powershell-2.0


【解决方案1】:

将 CSV 中的短名称值与正则表达式“OR”符号“|”结合起来
转义任何可能的正则表达式特殊字符

$shortname = (Import-Csv -Path 'c:\shortnameslist.csv' | ForEach-Object { [regex]::Escape($_.shortname) }) -join '|'
$regex = "^HOST($shortname).*END$"

$foldername = 'HOSTIFS-blahblahEND'  # "FOLDERABSNAME"
$foldername -match $regex  # --> True

如果返回 $true,则可以在 $matches[1] 中找到匹配的短名称

如果比较需要区分大小写,请将-match 更改为cmatch

【讨论】:

  • 感谢您的澄清。解决方案按预期工作。
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多