我如何使用PowerShell中抽取子?
我有这个字符串...
"-----start-------Hello World------end-------"
我要提取...
Hello World
什么是做到这一点的最好方法是什么?
该-match
运营商测试一个正则表达式,用魔术变$matches
让你的结果结合起来
PS C:\> $x = "----start----Hello World----end----"
PS C:\> $x -match "----start----(?<content>.*)----end----"
True
PS C:\> $matches['content']
Hello World
每当有关正则表达式-Y的东西疑问,看看这个网站:http://www.regular-expressions.info
该Substring
方法我们提供了一个方法来提取基于一个起始位置和长度的原始字符串的特定字符串。如果只提供一个参数,它被取为起始位置,和该字符串的剩余部分被输出。
PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >
但是,这是更简单...
$s = 'Hello World is in here Hello World!'
$p = 'Hello World'
$s -match $p
最后,通过目录递归只选择了.txt文件和搜索的“Hello World”的发生:
dir -rec -filter *.txt | Select-String 'Hello World'
不知道这是否是有效的或没有,但在PowerShell中的字符串可被称为使用数组索引的语法,以类似的方式到Python。
这不是完全直观的,因为事实的第一个字母是由index = 0
称,但它的作用:
这里有些例子:
PS > 'Hello World'[0..2]
得到的结果(包括对清晰度指数值 - 在输出不产生):
H [0]
e [1]
l [2]
这可以通过传递-join ''
进行更加有用:
PS > 'Hello World'[0..2] -join ''
Hel
还有,你可以通过使用不同的指标得到了一些有趣的效果:
前锋
使用第一指标值小于第二和子将在向前的方向被提取,你期望的那样。此时的第2指标值是远远超过串长度的但没有错误:
PS > 'Hello World'[3..300] -join ''
lo World
不同于:
PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.
向后
如果你提供第二索引值低于第一,字符串返回相反:
PS > 'Hello World'[4..0] -join ''
olleH
从结束
如果您使用负数可以参考的位置从字符串的结尾。要提取'World'
,最后5个字母,我们使用:
PS > 'Hello World'[-5..-1] -join ''
World
PS> $a = "-----start-------Hello World------end-------" PS> $a.substring(17, 11) or PS> $a.Substring($a.IndexOf('H'), 11)
$a.Substring(argument1, argument2)
- >在这里argument1
=开始要作为输出的子串的期望字母和argument2
=长度的位置。
这里17是字母表'H'
的指数,因为我们要打印,直到世界您好,我们的第二个参数提供11
其他的解决办法
$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"
$text | ConvertFrom-String -TemplateContent $template
马特的答案的基础上,这里是一个跨新行搜索,很容易修改自己使用
$String="----start----`nHello World`n----end----"
$SearchStart="----start----`n" #Will not be included in results
$SearchEnd="`n----end----" #Will not be included in results
$String -match "(?s)$SearchStart(?<content>.*)$SearchEnd"
$result=$matches['content']
$result
--
注意:如果你想对一个文件运行该记住获取内容返回数组不是一个单一的字符串。您可以解决此通过执行以下操作:
$String=[string]::join("`n", (Get-Content $Filename))
我需要提取日志文件中的几行和这个职位是解决我的问题有帮助,所以我想在这里将它添加的。如果有人需要提取muliple线,您可以使用脚本来获取一个匹配串词(我在寻找“根”)的索引和提取所有行的内容。
$File_content = Get-Content "Path of the text file"
$result = @()
foreach ($val in $File_content){
$Index_No = $val.IndexOf("Root")
$result += $val.substring($Index_No)
}
$result | Select-Object -Unique
干杯..!
由于串并不复杂,无需添加正则表达式的字符串。一个简单的比赛就可以了
$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World
$result = $matches[0]
$result
Hello World