替换为PowerShell脚本中的正则表达式不起作用

时间:2017-02-21 08:20:44

标签: regex powershell

我正在尝试使用带有以下模式的正则表达式从JSON文件中删除所有注释:

$mytext="{/* anytext */  'name':'myname'}"
$mytext -replace /\/\*.+?\*\/|\/\/.*(?=[\n\r])/g,''

表达式在JavaScript中运行良好,但在PowerShell中运行不正确。

2 个答案:

答案 0 :(得分:0)

  1. 您没有引用模式
  2. PowerShell不会使用/包装模式,并且/g(全局标记)不是必需的,因为-replace默认会使用它。
  3. 我还添加了\s*以删除评论后的不必要的空格

    尝试:

    $mytext="{'foo'='bar' /* anytext */  'name':'myname'} {'foo'='bar' /* anytext */  'name':'myname'}"
    $mytext -replace '\/\*.+?\*\/\s*|\/\/.*(?=[\n\r])'
    

    输出:

    {'foo'='bar' 'name':'myname'} {'foo'='bar' 'name':'myname'}
    

答案 1 :(得分:0)

Thanks for quick answer guys. I have tried both the patterns and it works well, the only issue i am facing for some places it move the value text in next line which makes json invalid. 

"bootstrap": {
        "base": "${app.dir}",
        "manifest": "bootstrap.json",
        "microloader": "b
        ootstrap.js ",      "
        css ": "
        bootstrap.css "     },      "
        output ": {         "
        base ": "
        $ {
            workspace.build.dir
        }
It should be like
"bootstrap": {`enter code here`
        "base": "${app.dir}",
        "manifest": "bootstrap.json",
        "microloader": "bootstrap.js",
        "css": "bootstrap.css"
    },
/* *anytext */
"output": {
        "base": "${workspace.build.dir}/${build.environment}/${app.name}"
    },