2

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
  • Try backslash the curly braces of your regular expression. Commented Jul 13, 2016 at 11:38

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.