【问题标题】:Powershell: Extract text from string using RegexPowershell:使用正则表达式从字符串中提取文本
【发布时间】:2012-08-03 02:21:42
【问题描述】:

在正则表达式方面,我完全是个菜鸟,有人可以帮忙吗?

我需要的是域,然后我需要将所有 (??) 替换为 .

我需要提取的内容:(11)ops-findb01(13)domain(3)com(0)

最终结果应如下所示:.ops-findb01.domain.com。

8/2/2012 3:37:59 PM 0908 PACKET  0000000002CC4F60 UDP Rcv 10.10.10.10  563a   Q [0001   D   NOERROR] A     (11)ops-findb01(13)domain(3)com(0)
8/2/2012 3:37:59 PM 0908 PACKET  0000000002C32810 UDP Rcv 10.10.10.10  6f24   Q [0001   D   NOERROR] A     (11)ops-findb01(13)domain(3)com(0)
8/2/2012 3:38:00 PM 0908 PACKET  00000000029EDC00 UDP Rcv 10.10.10.10  459a   Q [0001   D   NOERROR] A     (3)www(6)google(3)com(0)
8/2/2012 3:38:00 PM 0908 PACKET  0000000002CC4F60 UDP Rcv 10.10.10.10  d47e   Q [0001   D   NOERROR] PTR   (2)dr(7)_dns-sd(4)_udp(1)0(2)40(1)5(2)10(7)in-addr(4)arpa(0)
8/2/2012 3:38:00 PM 0908 PACKET  0000000002C32810 UDP Rcv 10.10.10.10  0b3c   Q [0001   D   NOERROR] PTR   (2)db(7)_dns-sd(4)_udp(1)0(1)0(1)5(2)10(7)in-addr(4)arpa(0)
8/2/2012 3:38:00 PM 0908 PACKET  00000000029EDC00 UDP Rcv 10.10.10.10  8890   Q [0001   D   NOERROR] A     (2)dl(6)javafx(3)com(0)
8/2/2012 3:38:00 PM 0908 PACKET  0000000002CC4F60 UDP Rcv 10.10.10.10  60e7   Q [0001   D   NOERROR] A     (7)trading(9)scottrade(3)com(0)

日志文件格式将始终如您所见

【问题讨论】:

    标签: regex string powershell text-extraction


    【解决方案1】:

    假设一次一行:

    $betterline = ($line -match "\(\d+\)(?:\w+\(\d+\))+$") -replace "\(\d+\)", "."

    这首先匹配行以获取结尾部分,然后将数字和括号替换为点。

    对于未来,我强烈建议您学习正则表达式 - 它简单而无价。正则表达式的一个很好的参考/教程是regular-expressions.info

    【讨论】:

    • 感谢您的帮助!!找到 1 个问题,应该是 [\w-] 因为它需要搜索连字符。看我在学习:o)
    【解决方案2】:

    这是另一个没有大量使用正则表达式的选项:

    Get-Content file.txt | Foreach-Object {
    
        #split the line by space
        $line = $_.split() 
    
        # get the last element and replace (one or more digits) with a dot
        $line[-1] = $line[-1] -replace '\(\d+\)','.' 
    
        #join the line back using a space
        $line -join ' ' # join the line back using a space
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2013-06-25
      • 2014-10-17
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多