【问题标题】:Regex pattern with embedded double quotes in PowerShellPowerShell 中嵌入双引号的正则表达式模式
【发布时间】:2019-01-12 15:37:14
【问题描述】:

需要使用 PowerShell 在文档上搜索以下关键字:

[“允许的采集清理期”
$keyword = ""
Get-Content $SourceFileName | Select-String -Pattern $keyword

我正在搜索的字符串中有双引号,所以我正在努力如何在这个$keyword 中提及。

【问题讨论】:

  • 提示:如果您不确定将来要逃避什么,可以使用[regex]::Escape() 方法。

标签: powershell escaping quoting


【解决方案1】:

显然你不仅有双引号,还有一个左方括号。方括号是正则表达式中的元字符(用于定义字符类),因此您也需要对它们进行转义。

用单引号定义你的表达式:

$keyword = '\["Allowed Acquisition Clean-Up Period"'

或用反引号转义嵌套的双引号:

$keyword = "\[`"Allowed Acquisition Clean-Up Period`""

【讨论】:

  • 以上不适用于 LIKE 子句 $SearchKeyword1 = '["Lookup keyword"' if ($para.Range.Text -Like $SearchKeyword1)
  • @user3657339 当然不是。正则表达式匹配(-matchSelect-String)和通配符匹配(-like相同,并且使用相同的模式。
【解决方案2】:

补充Ansgar Wiechers' helpful answer,其中包含正确的解决方案:

鉴于" 不是正则表达式元字符(在正则表达式中没有特殊含义),您的问题归结为:
如何将"(双引号)嵌入到PowerShell 中的字符串?

  • 顺便说一句:如上所述,[ 一个正则表达式元字符,因此它必须在正则表达式中转义为 \[ 才能被视为 文字时间>。正如TheIncorrigible1 指出的那样,您可以让[regex]::Escape($string) 为您处理转义;结果在正则表达式的上下文中处理$string 字面意思 的内容。

有几个选项,这里用一个简化的示例字符串演示,3 " of rain - 另请参阅:Get-Help about_Quoting_Rules

# Inside a *literal string* ('...'):
# The content of single-quoted strings is treated *literally*.
# Double quotes can be embedded as-is.
'3 " of rain'

# Inside an *expandable string* ("..."):
# Such double-quoted strings are subject to *expansion* (interpolation)
# of embedded variable references ("$var") and expressions ("$(Get-Date)")
# Use `" inside double quotes; ` is PowerShell's escape character.
"3 `" of rain"                                                                                 #"
# Inside "...", "" works too.
"3 "" of rain"

# Inside a *literal here-string* (multiline; end delimiter MUST be 
# at the very beginning of a line):
# " can be embedded as-is.
@'
3 " of rain
'@

# Inside an *expanding here-string*:
# " can be embedded as-is, too.
@"
3 " of rain
"@

为了完整起见:您可以通过其 Unicode 代码点创建双引号(标识每个字符的数字),即0x22(十六进制)/34(十进制),将其转换为 [char],例如:[char] 0x22
你可以使用这个:

  • 字符串连接中:'3 ' + [char] 0x22 + ' of rain'
  • 带有-f 运算符的字符串格式表达式中'3 {0} of rain' -f [char] 0x22

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多