【问题标题】:Powershell regular expression to replace a digit with a string of variable lengthPowershell正则表达式用可变长度的字符串替换数字
【发布时间】:2016-11-15 23:14:48
【问题描述】:

我有以下字符串

$FileNamePattern =  'blah_{4}_{5}_blah_{4}-{2}.CSV'

我想用一串问号替换花括号中的数字,n个字符长

作为一个例子,我希望它返回'blah_????_?????_blah_????-??.CSV'

到目前为止我有这个,但似乎无法让替换工作中的“扩展”工作

[regex]::Replace($FileNamePattern,'{(\d+)}','"?"*$1')

任何帮助将不胜感激!

马修

【问题讨论】:

  • 尝试反斜杠正则表达式的花括号。

标签: regex powershell replace expression


【解决方案1】:

你需要在回调方法中对匹配进行处理:

$callback = {  param($match) "?" * [int]$match.Groups[1].Value }
$FileNamePattern =  'blah_{4}_{5}_blah_{4}-{2}.CSV'
$rex = [regex]'{(\d+)}'
$rex.Replace($FileNamePattern, $callback)

正则表达式 {(\d+)} 匹配 {} 并在其间捕获 1+ 个数字。子匹配在回调中被解析为整数(参见[int]$match.Groups[1].Value),然后?"?" * [int]$match.Groups[1].Value 重复该次数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2014-06-24
    • 2018-07-13
    相关资源
    最近更新 更多