【问题标题】:search for certian words in a string搜索字符串中的某些单词
【发布时间】:2021-06-22 09:41:08
【问题描述】:

我正在努力编写一个简单的报告脚本。 例如

$report.FullFormattedMessage = "This is the deployment test for Servername for Stackoverflow in datacenter onTV"
$report.FullFormattedMessage.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                        
-------- -------- ----                                     --------                                                                                                        
True     True     String                                   System.Object  

现在我想挑出一些特定的词,比如...

$dc = should be the 'onTV'
$srv = should be the 'Servername'
$srv = $report.FullFormattedMessage.contains... or -match ?? something like this?

.split()[] 的技巧对我不起作用,因为 $report 有时看起来不同。我怎么能这样做?

【问题讨论】:

    标签: regex powershell output select-string


    【解决方案1】:

    哦,好的,我找到了解决方案,我不知道这是否是最好的......但我告诉你:

    $lines = $report.FullFormattedMessage.split() 
    
       $dc= ForEach ($line in $lines){
        
        $line | Where-Object {$_ -match "onTV*"} 
        }
        
        $srv= ForEach ($line in $lines){
        
        $line | Where-Object {$_ -match "Server*"} 
        }
    

    【讨论】:

      【解决方案2】:

      我可能会做类似的事情

      $report.FullFormattedMessage = "This is the deployment test for Servername for Stackoverflow in datacenter onTV"
      $dc  = if ($report.FullFormattedMessage -match '\b(onTV)\b') { $Matches[1] }        # see details 1
      $srv = if ($report.FullFormattedMessage -match '\b(Server[\w]*)') { $Matches[1] }   # see details 2
      
      # $dc   --> "onTV"
      # $srv  --> "Servername"
      

      正则表达式详细信息 1

      \b             Assert position at a word boundary
      (              Match the regular expression below and capture its match into backreference number 1
         onTV        Match the characters “onTV” literally
      )             
      \b             Assert position at a word boundary
      

      正则表达式细节 2

      \b             Assert position at a word boundary
      (              Match the regular expression below and capture its match into backreference number 1
         Server      Match the characters “Server” literally
         [\w]        Match a single character that is a “word character” (letters, digits, etc.)
            *        Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
      )
      

      【讨论】:

        猜你喜欢
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2013-10-22
        • 1970-01-01
        • 2020-05-01
        • 2022-01-24
        相关资源
        最近更新 更多