使用 PowerShell 提取子字符串

发布于 2024-09-04 07:47:27 字数 195 浏览 2 评论 0 原文

如何使用 PowerShell 提取子字符串?

我有这个字符串...

"-----start-------Hello World------end-------"

我必须提取...

Hello World

最好的方法是什么?

How can I extract a substring using PowerShell?

I have this string ...

"-----start-------Hello World------end-------"

I have to extract ...

Hello World

What is the best way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

御守 2024-09-11 07:47:27

-match 运算符测试正则表达式,将其与神奇变量 $matches 结合起来以获得结果

PS C:\> $x = "----start----Hello World----end----"
PS C:\> $x -match "----start----(?<content>.*)----end----"
True
PS C:\> $matches['content']
Hello World

每当对正则表达式有疑问时,请查看此站点:http://www.regular-expressions.info

The -match operator tests a regex, combine it with the magic variable $matches to get your result

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

瘫痪情歌 2024-09-11 07:47:27

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'

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.

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":

dir -rec -filter *.txt | Select-String 'Hello World'
等你爱我 2024-09-11 07:47:27

不确定这是否有效,但可以使用数组索引语法引用 PowerShell 中的字符串,与 Python 类似。

它不是完全直观,因为第一个字母是由index = 0引用的,但它确实:

  • 允许第二个索引号比字符串长,而不需要生成错误
  • 反向提取子字符串
  • 从字符串末尾提取子字符串

以下是一些示例:

PS > 'Hello World'[0..2]

产生结果(为了清晰起见,包括索引值 - 不在输出中生成):

H [0]
e [1]
l [2]

通过传递 -join ' 可以使其更有用'

PS > 'Hello World'[0..2] -join ''
Hel

通过使用不同的索引,您可以获得一些有趣的效果:

向前

使用小于第二个索引值的第一个索引值,子字符串将在您选择时向前提取会期望。这次第二个索引值远远超过了字符串长度,但没有错误:

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

从末尾

如果使用负数,则可以引用从字符串末尾开始的位置。要提取最后 5 个字母 'World',我们使用:

PS > 'Hello World'[-5..-1] -join ''
World

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.

It's not completely intuitive because of the fact the first letter is referred to by index = 0, but it does:

  • 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 '':

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:

PS > 'Hello World'[-5..-1] -join ''
World
树深时见影 2024-09-11 07:47:27

<前><代码>PS> $a = "-----开始-----Hello World------结束-----"
PS> $a.substring(17, 11)
或者
PS> $a.Substring($a.IndexOf('H'), 11)

$a.Substring(argument1, argument2) -->这里 argument1 = 所需字母表的起始位置,argument2 = 您想要作为输出的子字符串的长度。

这里 17 是字母表 'H' 的索引,因为我们想要打印直到 Hello World,所以我们提供 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.

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

尾戒 2024-09-11 07:47:27

以马特的答案为基础,这是一个跨换行符搜索的答案,并且很容易修改以供您自己使用

$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

-

注意:如果您想对文件运行此答案,请记住 Get-Content 返回一个数组而不是单个字符串。您可以通过执行以下操作来解决此问题:

$String=[string]::join("`n", (Get-Content $Filename))

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:

$String=[string]::join("`n", (Get-Content $Filename))
辞旧 2024-09-11 07:47:27

其他解决方案

$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"

$text | ConvertFrom-String -TemplateContent $template

other solution

$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"

$text | ConvertFrom-String -TemplateContent $template
美煞众生 2024-09-11 07:47:27

由于字符串并不复杂,因此无需添加 RegEx 字符串。简单的搭配就能达到目的

$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World

$result = $matches[0]
$result
Hello World

Since the string is not complex, no need to add RegEx strings. A simple match will do the trick

$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World

$result = $matches[0]
$result
Hello World
不交电费瞎发啥光 2024-09-11 07:47:27

通常,使用 [regex] 直接:

这是 -match & 的替代方案。 $matches 构建于 Matt 的答案

PS> $x = "----start----Hello World----end----"
PS> $pattern = "^-*start-*(.*?)-*end-*$"
PS> $found = [regex]::Matches($x,$pattern)
PS> $found

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 44
Value    : -----start-------Hello World------end-------

PS> $found.Groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 44
Value    : -----start-------Hello World------end-------

Success  : True
Name     : 1
Captures : {1}
Index    : 17
Length   : 11
Value    : Hello World

PS> $found.Groups[1].Value
Hello World

这使我们能够在字符串中找到多个匹配结果,但是我们并不真正需要分组在这里提供的功能,因此 look-behind &前瞻断言将允许我们在不捕获组的情况下进行匹配:

PS> $x = "----start----Hello World----end----"
PS> $pattern = "(?<=-*start-*)[\w\s]*?(?=-*end-*)"
PS> [regex]::Match($x,$pattern).Value
Hello World

PowerShell & .NET 正则表达式与普通正则表达式略有不同,因此请务必引用 快速参考指南以获取其他快捷方式。

Often it is easier to work with [regex] directly:

This is an alternative to -match & $matches building off of Matt's answer

PS> $x = "----start----Hello World----end----"
PS> $pattern = "^-*start-*(.*?)-*end-*
quot;
PS> $found = [regex]::Matches($x,$pattern)
PS> $found

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 44
Value    : -----start-------Hello World------end-------

PS> $found.Groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 44
Value    : -----start-------Hello World------end-------

Success  : True
Name     : 1
Captures : {1}
Index    : 17
Length   : 11
Value    : Hello World

PS> $found.Groups[1].Value
Hello World

This allows us to find multiple match results in a string but we don't really need that functionality that grouping provides here so look-behind & look-ahead assertions would allow us to match without capturing groups:

PS> $x = "----start----Hello World----end----"
PS> $pattern = "(?<=-*start-*)[\w\s]*?(?=-*end-*)"
PS> [regex]::Match($x,$pattern).Value
Hello World

PowerShell & .NET regex is slightly different than vanilla regex so be sure to reference the quick reference guide for additional shortcuts.

夏雨凉 2024-09-11 07:47:27

我需要在日志文件中提取几行,这篇文章有助于解决我的问题,所以我想在此处添加它。如果有人需要提取多行,您可以使用脚本获取与该字符串匹配的单词的索引(我正在搜索“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

干杯..!

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.

$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..!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文