【问题标题】:Filter results further based on pattern根据模式进一步过滤结果
【发布时间】:2018-07-16 05:37:21
【问题描述】:

使用 PowerShell,我们能够成功地从文档中提取我们需要的行。

代码:

Get-Content "C:\Contract.doc" | 
    Select-String -Pattern "in relation to any Facility" | 
    Select -Property @{Name = 'Name'; Expression = {$_.Line}}

输出:

姓名 ---- 就任何融资 A 贷款 [2%]%。每年; 与任何 B 贷款 [ 5% ]% 相关。每年;

我们正在寻找的是从上述输出中提取 2% ... 5%

我们正在尝试的代码对我们不起作用:

Get-Content "C:\Contract.doc" | 
    Select-String -Pattern "in relation to any Facility" | 
    Select -Property @{Name = 'Name'; Expression = {$_.Line}} |
    Select-String '\[\?+([^?]+)\?+\]' |
    ForEach-Object { $_.Matches.Groups[1].Value }

任何人都可以帮助如何提取如下:

“关于任何融资 A 贷款 [2% ] 每年百分比”、“2%”

Word Doc的一部分:合同文档

“保证金”是指: (a) 就任何融资 A 贷款 [2% ]%。每年; (b) 就任何融资 B 贷款 [5%]%。每年; (c) [就任何增量融资贷款而言,增量融资通知中规定的与提供或将要提供该增量融资贷款的增量融资有关的年利率;]

【问题讨论】:

  • 请同时提供C:\Contract.doc的(部分)内容。
  • 增加合约部分
  • 根据您之前的问题:您是否总是要提取方括号中的百分比或其他子字符串?你想提取的子串和不想提取的子串有什么区别?

标签: powershell


【解决方案1】:

检查下一个sn-p。

Get-Content C:\Contract.doc |
Select-String -Pattern @'
\b(in relation to any Facility [A-Z] Loan \[\s*(\d+%)\s*\] per cent. per annum);
'@ |
Select-Object @{Name = 'Line'; Expression = {$_.Matches.Groups[1].Value}},
              @{Name = 'Result'; Expression = {$_.Matches.Groups[2].Value}}

如需了解正则表达式\b(in relation to any Facility [A-Z] Loan \[\s*(\d+%)\s*\] per cent. per annum);,请点击here

【讨论】:

    【解决方案2】:

    使用Regular Expression,解决方案效率更高:

    Get-Content .\contract.doc|
      Where-Object {$_ -match 'in relation to any Facility.*\[([\d% ]+)\]'}| 
        ForEach-Object{
          [PSCustomObject]@{
            Name  = $_
            Value = $Matches[1].trim()
          }
        }
    

    我真的应该在发布类似答案之前向下滚动。

    【讨论】:

      【解决方案3】:

      试试这个:

      编辑:

      $FinalTable = Get-Content .\Contract.doc |
              select-string -pattern "in relation to any Facility" |
              Select -Property @{Name = 'Name'; Expression = {$_.Line}} |
              ForEach-Object {
              $str = $_.Name
              $start = $str.indexOf("[") + 1
              $end = $str.indexOf("]", $start)
              $length = $end - $start
      
              $result = ($str.substring($start, $length)).trim()
      
              #Creating a custom object to display in table format
              $Obj = New-Object -TypeName PSCustomObject
              Add-Member -InputObject $Obj -MemberType NoteProperty -Name Name -Value $str
              Add-Member -InputObject $Obj -MemberType NoteProperty -Name Value -Value $result
      
              $obj
          }
          $FinalTable
      

      【讨论】:

      • 非常好,得到了我正在寻找的价值。我们如何显示这样的请:“与任何设施 A 贷款 [2% ] 百分比。每年;”,2%
      • 进行了更改。您所要做的就是创建一个自定义对象并将您想要的项目作为它的属性放入其中。
      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 2011-08-24
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      相关资源
      最近更新 更多