Multiline regex to match config block

后端 未结 4 868
误落风尘
误落风尘 2020-11-27 17:41

I am having some issues trying to match a certain config block (multiple ones) from a file. Below is the block that I\'m trying to extract from the config file:



        
4条回答
  •  失恋的感觉
    2020-11-27 18:35

    This regex will search for the text ap followed by any number of characters and new lines ending with a !:

    (?si)(a).+?\!{1}
    

    So I was a little bored. I wrote a script that will break up the text file as you described (as long as it only contains the lines you displayed). It might work with other random lines, as long as they don't contain the key words: ap, profile, domain, hostname, or area. It will import them, and check line by line for each of the properties (MAC, Profile, domain, hostname, area) and place them into an object that can be used later. I know this isn't what you asked for, but since I spent time working on it, hopefully it can be used for some good. Here is the script if anyone is interested. It will need to be tweaked to your specific needs:

    $Lines = Get-Content "c:\test\test.txt"
    $varObjs = @()
    for ($num = 0; $num -lt $lines.Count; $num =$varLast ) {
        #Checks to make sure the line isn't blank or a !. If it is, it skips to next line
        if ($Lines[$num] -match "!") {
            $varLast++
            continue
        }
        if (([regex]::Match($Lines[$num],"^\s.*$")).success) {
            $varLast++
            continue
        }
        $Index = [array]::IndexOf($lines, $lines[$num])
        $b=0
        $varObj = New-Object System.Object
        while ($Lines[$num + $b] -notmatch "!" ) {
            #Checks line by line to see what it matches, adds to the $varObj when it finds what it wants.
            if ($Lines[$num + $b] -match "ap") { $varObj | Add-Member -MemberType NoteProperty -Name Mac -Value $([regex]::Split($lines[$num + $b],"\s"))[1] }
            if ($lines[$num + $b] -match "profile") { $varObj | Add-Member -MemberType NoteProperty -Name Profile -Value $([regex]::Split($lines[$num + $b],"\s"))[3] }
            if ($Lines[$num + $b] -match "domain") { $varObj | Add-Member -MemberType NoteProperty -Name rf-domain -Value $([regex]::Split($lines[$num + $b],"\s"))[3] }
            if ($Lines[$num + $b] -match "hostname") { $varObj | Add-Member -MemberType NoteProperty -Name hostname -Value $([regex]::Split($lines[$num + $b],"\s"))[2] }
            if ($Lines[$num + $b] -match "area") { $varObj | Add-Member -MemberType NoteProperty -Name area -Value $([regex]::Split($lines[$num + $b],"\s"))[2] }
            $b ++
        } #end While
        #Adds the $varObj to $varObjs for future use
        $varObjs += $varObj
        $varLast = ($b + $Index) + 2
    }#End for ($num = 0; $num -lt $lines.Count; $num = $varLast)
    #displays the $varObjs
    $varObjs
    

提交回复
热议问题