【问题标题】:PowerShell Regex replace produces empty outputPowerShell 正则表达式替换产生空输出
【发布时间】:2018-07-23 19:44:02
【问题描述】:

我正在尝试匹配以下字符串并将其替换为第一个捕获组:PCUNIT020\Username; 我只需要 用户名 部分。我使用以下正则表达式:

 $name="PCUNIT020\Username";
 $regex="^\w+\\(.*)";
 $newname=$name -replace $regex, $1;
 $newname;

shell 不输出任何东西。

【问题讨论】:

    标签: regex string powershell replace


    【解决方案1】:

    您的错误是您必须将$1 放在引号中:'$1'。否则,它只是用变量$1 的值替换所有内容,因此没有设置任何内容。

    但是,不要用第一个捕获组替换它,而是替换所有内容,直到包括反斜杠在内什么都没有:

    $name -replace '^\w+\\'
    

    【讨论】:

      猜你喜欢
      • 2012-06-20
      • 2016-02-13
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多