string 使用 PowerShell 提取子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2988880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract a substring using PowerShell
提问by achi
How can I extract a substring using PowerShell?
如何使用 PowerShell 提取子字符串?
I have this string ...
我有这个字符串...
"-----start-------Hello World------end-------"
I have to extract ...
我必须提取...
Hello World
What is the best way to do that?
最好的方法是什么?
回答by Matt Woodard
The -match
operator tests a regex, combine it with the magic variable $matches
to get your result
该-match
运营商测试一个正则表达式,用魔法变结合起来$matches
,让您的结果
PS C:\> $x = "----start----Hello World----end----"
PS C:\> $x -match "----start----(?<content>.*)----end----"
True
PS C:\> $matches['content']
Hello World
Whenever in doubt about regex-y things, check out this site: http://www.regular-expressions.info
每当对正则表达式有疑问时,请查看此站点:http: //www.regular-expressions.info
回答by nineowls
The Substring
method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.
该Substring
方法为我们提供了一种基于起始位置和长度从原始字符串中提取特定字符串的方法。如果仅提供一个参数,则将其作为起始位置,并输出字符串的其余部分。
PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >
But this is easier...
但这更容易...
$s = 'Hello World is in here Hello World!'
$p = 'Hello World'
$s -match $p
And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":
最后,递归遍历一个目录,只选择 .txt 文件并搜索“Hello World”的出现:
dir -rec -filter *.txt | Select-String 'Hello World'
回答by mjsqu
Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.
不确定这是否有效,但可以使用数组索引语法以类似于 Python 的方式引用 PowerShell 中的字符串。
It's not completelyintuitive because of the fact the first letter is referred to by index = 0
, but it does:
这不是完全直观的,因为事实的第一个字母是指通过index = 0
,但它的作用:
- Allow a second index number that is longer than the string, without generating an error
- Extract substrings in reverse
- Extract substrings from the end of the string
- 允许比字符串长的第二个索引号,而不会产生错误
- 反向提取子串
- 从字符串的末尾提取子字符串
Here are some examples:
这里有些例子:
PS > 'Hello World'[0..2]
Yields the result (index values included for clarity - not generated in output):
产生结果(为清楚起见,包括索引值 - 不在输出中生成):
H [0]
e [1]
l [2]
Which can be made more useful by passing -join ''
:
通过传递可以使其更有用-join ''
:
PS > 'Hello World'[0..2] -join ''
Hel
There are some interesting effects you can obtain by using different indices:
使用不同的索引可以获得一些有趣的效果:
Forwards
远期
Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:
使用小于第二个索引值的第一个索引值,子字符串将按照您的预期向前提取。这次第二个索引值远远超过字符串长度但是没有错误:
PS > 'Hello World'[3..300] -join ''
lo World
Unlike:
不同于:
PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.
Backwards
向后
If you supply a second index value that is lower than the first, the string is returned in reverse:
如果您提供的第二个索引值低于第一个,则该字符串将反向返回:
PS > 'Hello World'[4..0] -join ''
olleH
From End
从结束
If you use negative numbers you can refer to a position from the end of the string. To extract 'World'
, the last 5 letters, we use:
如果使用负数,则可以引用字符串末尾的位置。要提取'World'
,最后 5 个字母,我们使用:
PS > 'Hello World'[-5..-1] -join ''
World
回答by Vivek Kumar Singh
PS> $a = "-----start-------Hello World------end-------" PS> $a.substring(17, 11) or PS> $a.Substring($a.IndexOf('H'), 11)
PS> $a = "-----start-------Hello World------end-------" PS> $a.substring(17, 11) or PS> $a.Substring($a.IndexOf('H'), 11)
$a.Substring(argument1, argument2)
--> Here argument1
= Starting position of the desired alphabet and argument2
= Length of the substring you want as output.
$a.Substring(argument1, argument2)
--> 这里argument1
= 所需字母表的起始位置和argument2
= 您想要作为输出的子串的长度。
Here 17 is the index of the alphabet 'H'
and since we want to Print till Hello World, we provide 11 as the second argument
这里 17 是字母表的索引,'H'
因为我们要打印到 Hello World,所以我们提供 11 作为第二个参数
回答by Esperento57
other solution
其他解决方案
$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"
$text | ConvertFrom-String -TemplateContent $template
回答by Chris Rudd
Building on Matt's answer, here's one that searches across newlines and is easy to modify for your own use
基于马特的回答,这里有一个跨换行搜索并且很容易修改以供您自己使用
$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
--
——
NOTE: if you want to run this against a file keep in mind Get-Content returns an array not a single string. You can work around this by doing the following:
注意:如果你想对一个文件运行这个,请记住 Get-Content 返回一个数组而不是单个字符串。您可以通过执行以下操作来解决此问题:
$String=[string]::join("`n", (Get-Content $Filename))
回答by pause-ee-tive
I needed to extract a few lines in a log file and this post was helpful in solving my issue, so i thought of adding it here. If someone needs to extract muliple lines, you can use the script to get the index of the a word matching that string (i'm searching for "Root") and extract content in all lines.
我需要在日志文件中提取几行,这篇文章对解决我的问题很有帮助,所以我想在这里添加它。如果有人需要提取多行,您可以使用脚本获取与该字符串匹配的单词的索引(我正在搜索“Root”)并提取所有行中的内容。
$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
Cheers..!
干杯..!
回答by user3688297
Since the string is not complex, no need to add RegEx strings. A simple match will do the trick
由于字符串并不复杂,因此无需添加 RegEx 字符串。一个简单的匹配就可以解决问题
$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World
$result = $matches[0]
$result
Hello World