Powershell正则表达式以一串可变长度来替换一个数字。

时间:2021-07-31 12:39:22

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

我想把花括号里的数字换成一串问号,n个字符长

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

作为一个例子我想它返回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 个解决方案

#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.

regex {(\d+)}匹配{和}并捕获中间的1+位数。子匹配被解析为回调内部的一个整数(参见[int]$match.Groups[1].Value),然后是?用“?”来重复这个次数?*(int)$ match.Groups[1]value。

Powershell正则表达式以一串可变长度来替换一个数字。

#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.

regex {(\d+)}匹配{和}并捕获中间的1+位数。子匹配被解析为回调内部的一个整数(参见[int]$match.Groups[1].Value),然后是?用“?”来重复这个次数?*(int)$ match.Groups[1]value。

Powershell正则表达式以一串可变长度来替换一个数字。