string 在powershell中提取部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35151598/
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 Part of a string in powershell
提问by Mustafa Salam
I am trying to extract 2 pieces of information from a string value. The first in from the 4th last to the 2nd last character; the second is from the 2nd last to the last character. This is the code I'm using:
我正在尝试从字符串值中提取 2 条信息。从倒数第 4 个字符到倒数第 2 个字符的第一个;第二个是从倒数第二个字符到最后一个字符。这是我正在使用的代码:
foreach ($item in $List)
{
$len = $item.Length
$folder1 = $item.Substring(($len - 2), $len)
$folder2 = $item.Substring(($len - 4), ($len - 2))
..
}
This code keeps throwing an error on the Substring function. The error description is as below:
此代码不断在 Substring 函数上引发错误。错误描述如下:
*Exception calling "Substring" with "2" argument(s): "Index and length must refer to a
location within the string.
Parameter name: length"
At line:7 char:1
+ $str.Substring($flen - 2, $slen)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException*
How do I use Substring? What should I pass as the correct parameters?
如何使用子字符串?我应该传递什么作为正确的参数?
回答by Paul Hicks
Substring
takes an index and a length parameter. You're passing in an index and an index parameter. If you want two characters from 4th-last character, the code is
Substring
接受一个索引和一个长度参数。您正在传入一个索引和一个索引参数。如果你想要倒数第四个字符的两个字符,代码是
$item.Substring($len - 5, 2)
Note that the index is 0-based, not 1-based.
请注意,索引是基于 0 的,而不是基于 1 的。