regex - 在powershell中获取文件名中正则表达式的索引

标签 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)
}

理想情况下,这应该可行,但因为 indexofany 不能像我那样处理正则表达式。

最佳答案

您可以使用 Regex.Match() method 执行正则表达式匹配。它将返回一个 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
    }
}

或者,使用 -match 运算符和 $Matches 变量来获取匹配的字符串并将其用作 IndexOf() 的参数(使用 RedLaser's sweet regex optimization ):
if($_.Name -match 's+\d{2,}e+\d{2,}')
{
    $Index = $_.Name.IndexOf($Matches[0])
    $ThingsBeforeMatch = $_.Name.Substring(0,$Index)
}

关于regex - 在powershell中获取文件名中正则表达式的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213219/

相关文章:

python - Pandas Dataframe 上的条件正则表达式函数

regex - 匹配 foo 或 bar vim 正则表达式

PowerShell - 删除txt文件中单词之间的空格

powershell - 使用 Powershell,如何获取给定服务名称的 Azure VIP?

php - 如何隔离内容直到第一个双换行序列?

ios - 在字符串中获取多个范围的动态字符串

python - 如何编写正则表达式来匹配重复模式的一小部分?

java - 正则表达式允许 java 中的特定特殊字符

Powershell:文件元数据中的 NTFS 路径与 New-ItemProperty、Set-ItemProperty?

mysql - 在 MySQL 条件中使用子字符串