Powershell正则表达式用可变长度的字符串替换数字 [英] Powershell regular expression to replace a digit with a string of variable length
问题描述
我有以下字符串
$ FileNamePattern ='blah_ {4} _ {5} _blah_ {4} - { 2} .CSV'
我想用大括号中的数字替换一个问题的字符串标记,n个字符长
作为一个例子,我希望它返回'blah _ ???? _ ????? _ blah_? ?? - ??。CSV'
我到目前为止,但似乎没有得到扩展的替换工作
[regex] ::替换($ FileNamePattern,'{(\d +)}','? $ 1')
任何帮助将不胜感激!
Matthew
您需要在回调方法内进行匹配处理:
$ 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
。
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
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
.
这篇关于Powershell正则表达式用可变长度的字符串替换数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!