sim*_*mon 5 regex powershell substring indexof
我正在尝试获取文件夹名称中正则表达式匹配的起始位置。
dir c:\test | where {$_.fullname.psiscontainer} | foreach {
$indexx = $_.fullname.Indexofany("[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]")
$thingsbeforeregexmatch.substring(0,$indexx)
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,这应该可行,但由于 indexofany 不处理正则表达式,所以我陷入了困境。
您可以使用该Regex.Match()方法来执行正则表达式匹配。它将返回一个MatchInfo具有您可以使用的属性的对象Index:
Get-ChildItem c:\test | Where-Object {$_.PSIsContainer} | ForEach-Object {
# Test if folder's Name matches pattern
$match = [regex]::Match($_.Name, '[Ss]+[0-9]+[0-9]+[Ee]+[0-9]+[0-9]')
if($match.Success)
{
# Grab Index from the [regex]::Match() result
$Index = $Match.Index
# Substring using the index we obtained above
$ThingsBeforeMatch = $_.Name.Substring(0, $Index)
Write-Host $ThingsBeforeMatch
}
}
Run Code Online (Sandbox Code Playgroud)
或者,使用-match运算符和$Matches变量来获取匹配的字符串并将其用作参数IndexOf()(使用RedLaser 的甜蜜正则表达式优化):
if($_.Name -match 's+\d{2,}e+\d{2,}')
{
$Index = $_.Name.IndexOf($Matches[0])
$ThingsBeforeMatch = $_.Name.Substring(0,$Index)
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 Match 对象的 Index 属性。例子:
# Used regEx fom @RedLaser's comment
$regEx = [regex]'(?i)[s]+\d{2}[e]+\d{2}'
$testString = 'abcS00E00b'
$match = $regEx.Match($testString)
if ($match.Success)
{
$startingIndex = $match.Index
Write-Host "Match. Start index = $startingIndex"
}
else
{
Write-Host 'No match found'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10990 次 |
| 最近记录: |