Powershell - 提取特定子字符串之前和之后的字符串

问题描述 投票:0回答:1

我正在尝试找到一种方法来提取一行中特定子字符串之前和之后的所有文本。

从下面的示例中,我想要一种以编程方式查找 TEXT1 和 TEXT2 的方法。我假设我需要找到 c:\ 的索引,然后修剪直到找到第一个空格。然后还找到 test\ 并向前修剪直到下一个空格。

注意:同一行上可以有多个 c: est est\ 实例。

Other text for other things here blah blah TEXT1c:\test\test\ TEXT2 other garbage text here blah blah

我可以在找到的字符串上来回修剪 X 个字符,但这对于下一个空格来说是未知的数量。

powershell text-parsing
1个回答
0
投票

这并不优雅,但确实有效。

PS> $x = "This is junk Text1C:\Test\Test\ Text2 more junk"
#Find Text1 and add it's length to the answer
$y = $x.IndexOf("Text1") + 5
#Find Text2 and subtract $y go get length of substring
$Z = $x.IndexOf("Text2") - $y
#Extract your desired value and trim off trailing blanks
$ans = ($x.Substring($y,$z)).Trim()
$ans

结果:

C:\Test\Test\
© www.soinside.com 2019 - 2024. All rights reserved.