Powershell regular expression to replace a digit w

2019-05-21 09:41发布

I have the following string

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

and I want to replace the numbers in the curly braces with a string of question marks, n characters long

As an example I would like it to return 'blah_????_?????_blah_????-??.CSV'

I have this so far, but can't seem to get the 'expansion' in the replace working

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

Any help would be greatly appreciated!

Matthew

1条回答
Lonely孤独者°
2楼-- · 2019-05-21 10:02

You need to do the processing of the match inside a callback method:

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

The regex {(\d+)} matches { and } and captures 1+ digits in between. The submatch is parsed as an integer inside the callback (see [int]$match.Groups[1].Value) and then the ? is repeated that amount of times with "?" * [int]$match.Groups[1].Value.

enter image description here

查看更多
登录 后发表回答