通过RegEx解析带有不同引号的输入字符串



我需要通过Powershell将具有多个单词的输入字符串转换为字符串数组。单词可以用多个空格和/或换行符分隔。每个单词可以通过单引号或双引号进行转义。有些词可能以标签开头——在这种情况下,引号会出现在标签后面。

下面是一个可能输入和预期结果的代码示例:

$inputString = @"
test1
#custom1
#"custom2"           #'custom3'
#"custom ""four"""   #'custom ''five'''
test2 "test3" 'test4'
"@
$result = @(
'test1'
'#custom1'
'"#custom2"'
"#'custom3'"
'#"custom ""four"""'   
"#'custom ''five'''"
'test2' 
'"test3"' 
"'test4'"
)

是否有任何解决方案,通过一个聪明的regex表达式?或者有人有一个解析器片段/函数开始?

假设您完全控制或隐式信任输入字符串,您可以使用以下方法,该方法依赖于Invoke-Expression,通常应避免使用:

:

  • #只出现在嵌入字符串的开头处。
  • 没有嵌入字符串本身包含换行符。
$inputString = @"
test1
#custom1
#"custom2"           #'custom3'
#"custom ""four"""   #'custom ''five'''
test2 "test3" 'test4'
"@
$embeddedStrings = Invoke-Expression @"
Write-Output $($inputString -replace 'r?n', ' ' -replace '#', '`#')
"@

注意:单个字符串周围的外部引号在处理过程中丢失,嵌入的转义的引号未转义的;输出$embeddedString产率:

test1
#custom1
#custom2
#custom3
#custom "four"
#custom 'five'
test2
test3
test4

这种方法依赖于这样一个事实:你嵌入的字符串使用PowerShell的引号和引号转义规则;唯一的问题是前面的#字符,它们被转义为上面的`#。通过用空格替换嵌入的换行符(r?n),结果可以作为位置参数列表传递给Write-Output,在字符串中,然后用Invoke-Expression求值,这使得Write-Output逐个输出解析后的参数,作为变量$embeddedStrings中的数组捕获。

最新更新