Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 提取找到匹配项的子字符串_String_Powershell_Search_Substring_Powershell 3.0 - Fatal编程技术网

String 提取找到匹配项的子字符串

String 提取找到匹配项的子字符串,string,powershell,search,substring,powershell-3.0,String,Powershell,Search,Substring,Powershell 3.0,我有一个有很多行的文本文件。我想在每一行中分别搜索一个特定的模式,如果找到了该模式,则在与找到该模式的位置相关的特定位置输出一个子字符串 i、 e.如果一行包含位置20处的模式,我想输出从同一行的位置25开始并持续五个字符的子字符串 以下代码将输出包含模式的每一行: select-string -path C:\Scripts\trimatrima\DEBUG.txt -pattern $PATTERN 我从这里到哪里去?您可以使用$Matches自动变量: 最后一个匹配项存储在$Match

我有一个有很多行的文本文件。我想在每一行中分别搜索一个特定的模式,如果找到了该模式,则在与找到该模式的位置相关的特定位置输出一个子字符串

i、 e.如果一行包含位置20处的模式,我想输出从同一行的位置25开始并持续五个字符的子字符串

以下代码将输出包含模式的每一行:

select-string -path C:\Scripts\trimatrima\DEBUG.txt -pattern $PATTERN 

我从这里到哪里去?

您可以使用
$Matches
自动变量:

最后一个匹配项存储在
$Matches[0]
中,但您也可以使用命名的捕获组,如下所示:

"test","fest","blah" |ForEach-Object {
    if($_ -match "^[bf](?<groupName>es|la).$"){
        $Matches["groupName"]
    }
}
“test”、“fest”、“blah”|每个对象{
如果($匹配“^[bf](?es | la)。$”){
$Matches[“groupName”]
}
}
返回
es
(来自“fest”)和
la
(来自“blah”)

两个选项

保持
Select String
,您将希望使用
.line
属性获取子字符串:

select-string -path C:\Scripts\trimatrima\DEBUG.txt -pattern $PATTERN |
 foreach { $_.line.Substring(19,5) }
对于大型文件,
使用
-ReadCount
-match
获取内容可能更快:

Get-Content C:\Scripts\trimatrima\DEBUG.txt-ReadCount 1000 |
 foreach {
  $_ -match $pattern |
  foreach { $_.substring(19,5) }
  }

>我该怎么办?我认为,如果在后面提到一个积极的观点,那会很有帮助,因为使用第二种方法,他可以做一些类似于
GC$file-readcount 1000 | ForEach{$|-replace”的事情(?你不需要向后看。只需添加行锚的开头,并通配符前20个字符。从他的原始帖子中,我的印象是字符串可以位于行中的任何位置,他希望在模式后5个字符的子字符串,无论在哪里找到模式。我可能误解了d、 我也是这么看的。看起来这个问题是在我发布了这个答案后编辑的。