如何从字符串中提取 PowerShell 子字符串

  1. 使用 Substring() 方法提取 PowerShell 子字符串
  2. 在字符串左侧提取 PowerShell 子字符串
  3. 在指定字符之前和之后提取 PowerShell 子字符串
  4. 在两个字符之间提取 PowerShell 子字符串
如何从字符串中提取 PowerShell 子字符串

本文说明了如何在 PowerShell 中从字符串中提取子字符串。子字符串只是字符串的一部分。

我们可以使用 Substring()split() 方法在 PowerShell 中创建子字符串。比如,如果我们有字符串 Delftstack.comDelftstack 是一个子字符串,而 com 是另一个。

本文将讨论 Substring() 方法。

使用 Substring() 方法提取 PowerShell 子字符串

让我们先看一下 Substring() 方法的语法。

string.Substring(int startIndex, int length)

语法中的 int 标记 startIndexlength 为索引数字。startIndex 表示我们想要提取的子字符串的第一个字符,而 length 是我们想要从字符串中提取的字符数。

我们使用 IndexOf 方法来确定子字符串的 startIndexlength

我们通过将 IndexOf 子字符串的结果值加 1 来确定 startIndex。让我们看一个例子。

假设 ned.delftstack.com 是我们的字符串,那么字母 n 在我们字符串中的索引位置是什么?我们可以通过运行下面的命令来确定这个位置:

"ned.delftstack.com".IndexOf('n')

结果是 0。这是因为 IndexOf 方法从左到右搜索字符串的第一次出现,并且总是从 0 开始。

因此,如果我们希望提取从字母 n 开始的子字符串,我们的 startIndex 将是 0。

我们还可以使用 LastIndexOf 来找到字符串最后一次出现的位置。比如,字母 d 的最后一次出现位置是:

"ned.delftstack.com".LastIndexOf('d')

这些基本信息将使您能够在 PowerShell 中处理字符串。

在字符串左侧提取 PowerShell 子字符串

让我们将上述信息付诸实践。

假设我们想从 ned.delftstack.com 中提取子字符串 ned。我们该怎么做?

我们将首先将字符串保存在一个名为 ourstrng 的变量中。

$ourstrng = "ned.delftstack.com"

根据 Substring() 方法的语法,我们的命令将是:

$ourstrng.Substring(0, 3)

这将返回 ned,因为我们的 startIndex0length 是 3 个字符。如果我们的目标是从我们的字符串中提取 delftstack 呢?

第一步是确定子字符串的 startIndex。在这种情况下,我们将使用第一个句号,它是分隔符。

$ourstrng.IndexOf(".")

结果将是 3。但是如果您能回想起来,我们为字符串的第一个字符加 1;因此,我们的 startIndex 将是 4

长度将是我们希望子字符串拥有的字符数;我们将从 1 开始计数。子字符串 delftstack10 个字符。

$ourstrng.Substring(4, 10)

这将返回 delftstack

在指定字符之前和之后提取 PowerShell 子字符串

假设我们想从我们的字符串中提取 neddelftstack.com。我们该怎么做?

首先,我们需要确定分隔符的位置,第一个 .。下面的命令将分隔符保存在一个名为 $sepchar 的变量中。

$sepchar = $ourstrng.IndexOf(".")

要提取我们的子字符串,我们将运行下面的命令:

$ourstrng.Substring(0, $sepchar)

这将提取第一部分,即 ned。对于另一个子字符串,我们将运行:

$ourstrng.Substring($sepchar + 1)

这将返回 deftstack.com

在两个字符之间提取 PowerShell 子字符串

如果我们的字符串是 ned.delftstack.com,我们的子字符串将是 delftstack,因为它位于第一个和第二个句号之间。这样的脚本将需要三个命令。

第一个命令将确定我们第一个句号 (.) 的位置并将其保存到变量 firstsep 中。

$firstsep = $ourstrng.IndexOf(".")

第二个命令将使用 LastIndexOf 方法确定我们的第二个句号的位置,并将其保存到变量 lastrep 中。

$lastrep = $ourstrng.LastIndexOf(".")

最后一个命令将从我们的字符串中提取子字符串 delftstack

$ourstrng.Substring($firstsep + 1, $lastrep - 4)

总之,您可以在 PowerShell 分隔符之前、之后和之间提取字符串中的子字符串。正如我们上面所看到的,Substring() 方法非常实用。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相关文章 - PowerShell String