【问题标题】:RegEx: Find multiple results in JSON, but only in specific field, ignore other fieldsRegEx:在 JSON 中查找多个结果,但仅在特定字段中,忽略其他字段
【发布时间】:2017-10-06 07:26:40
【问题描述】:

使用 RegEx,并在 powershell 中使用它,我想在 json 的特定字段中查找所有反斜杠,必须忽略其他字段值

示例:在“查找”字段中查找所有反斜杠,而不是在此源中的替换字段中查找所有反斜杠

{
    "Find"   :  "<HintPath>([\.]{2}\\){1}Common\\Debug\\",
    "Replace":  "<HintPath>..\Common\Release\"
},
{
    "Find"   :  "<HintPath>([\.]{2}\\){2}Common\\Debug\\",
    "Replace":  "<HintPath>..\..\Common\Release\"
},
{
    "Find"   :  "<HintPath>([\.]{2}\\){3}Common\\Debug\\",
    "Replace":  "<HintPath>..\..\..\Common\Release\"
},
{
    "Find"   :  "<HintPath>([\.]{2}\\){4}Common\\Debug\\",
    "Replace":  "<HintPath>..\..\..\..\Common\Release\"
},
{
    "Find"   :  "<HintPath>([\.]{2}\\){5}Common\\Debug\\",
    "Replace":  "<HintPath>..\..\..\..\..\Common\Release\"
},
{
    "Find"   :  "<HintPath>([\.]{2}\\){6}Common\\Debug\\",
    "Replace":  "<HintPath>..\..\..\..\..\..\Common\Release\"
}

这对我不起作用:

(?<="Find")\\(?=\",)

【问题讨论】:

  • 那行得通 :) 如果您能详细解释正则表达式,那就太好了?谢谢
  • 编辑:如果我删除“,”和“替换”之间的换行符,它仍然匹配替换字段中的所有反斜杠。我们能以某种方式避免这种情况吗?
  • 您似乎接受了一些用户输入并放入 JSON。您需要在将用户输入 放入 JSON 之前对其进行操作。因此,与其解决问题,不如从一开始就避免它。
  • JSON 没有“字段”。这只是一个字符串。如果你想用 JSON 做事,那么解析它并用结果对象做事。尝试使用正则表达式处理/操作 JSON 或任何其他非平凡语言是愚蠢的差事。

标签: json regex powershell


【解决方案1】:

这在 powershell 中有效($text 包含 json 字符串):

$find_regex = '\S*["'']Find["''][^"'']*["''](.*)["''],'
$result= Select-String $find_regex -InputObject $text -AllMatches
foreach($match in $result.matches) {
$backslash_escaped = $match.Groups[1].value -replace '\\','\\'
$text = $text -replace [Regex]::Escape($match.Groups[1].value), $backslash_escaped
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多