Regex pattern with embedded double quotes in PowerShell

坚强是说给别人听的谎言 提交于 2020-12-31 16:38:40

问题


Following keyword need to be searched on document using PowerShell:

["Allowed Acquisition Clean-Up Period" 
$keyword = ""
Get-Content $SourceFileName | Select-String -Pattern $keyword

String which I'm searching for has double quotes in it, so I'm struggling how to mention in this $keyword.


回答1:


Apparently you not only have double quotes, but also an opening square bracket. Square brackets are meta-characters in regular expressions (for defining character classes), so you need to escape those too.

Define your expression in single quotes:

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

or escape nested double quotes with backticks:

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



回答2:


To complement Ansgar Wiechers' helpful answer, which contains the correct solution:

Given that " is not a regex metacharacter (has no special meaning in a regular expression), your question boils down to:
How can I embed a " (double quote) in a string in PowerShell?.

  • As an aside: As stated, [ is a regex metacharacter, so it must be escaped as \[ inside a regex in order to be treated as a literal. As TheIncorrigible1 points out, you can let [regex]::Escape($string) handle that escaping for you; the result treats the content of $string literally in the context of a regex.

There are several options, demonstrated here with a simplified sample string, 3 " of rain - see also: 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
"@

For the sake of completeness: you can create a double quote via its Unicode code point (the number that identifies each character), which is 0x22 (hex) / 34 (decimal), by casting it to [char], e.g.: [char] 0x22.
You can use this:

  • in string concatenations: '3 ' + [char] 0x22 + ' of rain'
  • in string-formatting expressions with the -f operator: '3 {0} of rain' -f [char] 0x22


来源:https://stackoverflow.com/questions/51694711/regex-pattern-with-embedded-double-quotes-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!