在 Powershell 中第二个句点后获取文本的子字符串 [英] Substring to Get Text after Second Period in Powershell

查看:38
本文介绍了在 Powershell 中第二个句点后获取文本的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个子字符串,它将在第二个 '.' 之前为我提供所有内容.我之前使用过子字符串来获取第一个 '.' 之前的所有内容

I am working with a Substring that will give me everything before the 2nd '.' I've worked with substrings before to get everything before the 1st '.'

$id = $file.Substring(0, $File.LastIndexof('.'))

它完美地工作.对于第二个子字符串,这是我迄今为止所拥有的

and it works perfectly. For this second substring this is what I have thus far

$netVerShort = $netVer.Substring(0,  2nd ('.'))

但我确定这是不对的.我从 $netVer 获得的值是 2.0.5727 并且使用第二个子字符串我试图让它返回 2.0

but I'm certain this isn't right. The value I get from $netVer is 2.0.5727 and with this second substring I'm trying to get it to return 2.0

推荐答案

不一定是最有效的方法,但您可以为此使用 split 并重新加入您要查找的元素.取以下字符串:

Not necessarily the most efficient approach but you could use split for this and rejoin the elements you are looking for. Take the following string:

$stuff = "This.is the end. Bagels. are. awesome."

现在我们将其拆分为句点,然后取前两个元素并将它们重新组合在一起.

Now we split that on periods and then take the first two elements and join them back together.

PS C:\Users\mcameron> $stuff.Split(".",3)
This
is the end
 Bagels. are. awesome.

3就是说我们只需要返回3个元素.根据您有多少个时期,这可能是一个不错的主意,以免浪费时间.接下来我们需要加入你想要的2个元素.

The 3 is to say that we only need to return 3 elements. Depending on how many periods you have this might be a good idea as to not waste time. Next we need to join the 2 elements you want.

PS C:\Users\mcameron> ($stuff.Split(".",3) | Select -Index 0,1) -join "."
This.is the end

要解决您的 .SubString() 方法,您需要检查两次,因为您将拥有第一个,然后您需要找到第二个.

To address your .SubString() approach you would need to check twice since you would have the first one then you would need to find the second.

PS C:\Users\mcameron> $stuff.Substring($stuff.IndexOf(".",$stuff.IndexOf(".") + 1))
. Bagels. are. awesome.

使用 $stuff.IndexOf(".") 获取第一个索引,然后在返回值中加 1.使用该值作为搜索下一个时期的起始索引.然后将其用于子字符串.如果您不希望该期间成为回报的一部分,则在整个事物中加 1.

Get the first index with $stuff.IndexOf(".") then add 1 to the return. Using that value as the start index for the search of the next period. Then use that for the substring. Add 1 to the entire thing if you dont want the period to be part of the return.

这篇关于在 Powershell 中第二个句点后获取文本的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆