从字符串中提取子字符串

时间:2018-07-15 08:18:26

标签: powershell

正在努力使用PowerShell从字符串下面的方括号中提取值

in relation to any Facility C Loan [?10%?] per cent. per annum;
"Facility A Commitments" means the aggregate of the Facility A Commitments, being [????????10 million?????] at the date of this Agreement.

需要的输出:

10%
10 million

3 个答案:

答案 0 :(得分:0)

这是这两种情况的正则表达式:

(?<=\[\?+)[^\?]*(?=\?+\])

您可以在https://regex101.com上玩它 但是,这不支持非固定宽度的后跟(第一个加号)。不过,它应该可以在.NET / PowerShell中工作。

这对您有好处:

https://www.regular-expressions.info/lookaround.html

答案 1 :(得分:0)

在内存(PSv4 +)中具有单个多行字符串:

$str = @'
in relation to any Facility C Loan [?10%?] per cent. per annum;
"Facility A Commitments" means the aggregate of the Facility A Commitments, being [????????10 million?????] at the date of this Agreement.
'@

[regex]::matches($str,'\[\?+([^?]+)\?+\]').ForEach({ $_.Groups[1].Value })

使用带有Get-ContentSelect-String的管道进行逐行处理(PSv3 +):

$lines = @'
in relation to any Facility C Loan [?10%?] per cent. per annum;
"Facility A Commitments" means the aggregate of the Facility A Commitments, being [????????10 million?????] at the date of this Agreement.
'@ -split '\r?\n'

# Substitute your `Get-Content someFile.txt` call for $lines
$lines |
  Select-String '\[\?+([^?]+)\?+\]' |
    ForEach-Object { $_.Matches.Groups[1].Value }

正则表达式\[\?+([^?]+)\?+\]的解释:

  • \[与文字[匹配
  • \?+匹配一个或多个(+)文字?
  • ([^?]+)是一个捕获组((...)),它与 not字符集(+)中的一个或多个([...])字符匹配^)的一部分,即不是?字符的 的任何字符-这是要提取的感兴趣的值。
  • \?+匹配一个或多个文字?
  • \]与文字]匹配

[regex]::Matches().Matches发出的对象上的Select-String属性是[System.Text.RegularExpressions.Match]对象的集合,它们的.Groups属性包含两个完全匹配项(索引0)和每个捕获组捕获的内容(1包含第一个捕获组的值,...)。

答案 2 :(得分:-1)

第一次运行:

$message -match '\[\?(\d*%)\?\]'
echo $Matches[1]

第二个:

\[\?*(\d* million)\?*\]
echo $Matches[1]

在每次迭代中,您都可以像检查$message -match '...'返回$ True一样简单,然后检查$ Matches变量中的值(这是一个保存正则表达式结果的系统变量。

相关问题