我有一个类似以下行的文件:
setmessage id=xxx.yyy.1 "text=Your input is not correct."
setmessage id=xxx.yyy.2 "text=Please add a ""Valid from"" date."
setmessage "id=xxx.yyy.3" "text=Another text, but the ID is in quotes too."
我的目标是将此文本拆分为不同的属性:
id => 'xxx.yyy.1'
text => 'Your input is not correct.'
id => 'xxx.yyy.2'
text => 'Please add a ""Valid from"" date.'
id => 'xxx.yyy.3'
text => 'Another text, but the ID is in quotes too.'
我目前使用的是这个:
function extractAttribute([String] $line, [String] $attribute){
if ($line -like "*$attribute*"){
$return = $line -replace ".*(?=`"$attribute=)`"$attribute=([^`"]*).*|.*$attribute=(.*?)([\r\n].*|$)", "`$1`$2"
if ($return -eq ""){
$return = $null
}
return $return
} else {
return $null
}
}
使用该代码,我可以一次提取一个属性。但它不适用于双引号:
$line = 'setmessage id=xxx.yyy.2 "text=Please add a ""Valid from"" date."'
$attribute = "text"
$result = extractAttribute $line $attribute
结果是:
'Please add a '
其余的都不见了。预期的结果应该是:
'Please add a ""Valid from"" date.'
有人可以帮助我吗?
谢谢!
编辑:我创建了一个穷人解决方案,用其他东西替换坏的双引号,然后拆分文本并再次替换。不好,但有效:
function extractAttribute([String] $line, [String] $attribute){
if ($line -like "*$attribute*"){
$line = $line -replace '""', '~~'
$return = $line -replace ".*(?=`"$attribute=)`"$attribute=([^`"]*).*|.*$attribute=(.*?)([\r\n ].*|$)", "`$1`$2"
$return = $return -replace '~~', '""'
if ($return -eq ""){
return $null
} else {
return $return
}
} else {
return $null
}
}