PowerShell to remove text from a string

前端 未结 5 546
不思量自难忘°
不思量自难忘° 2020-12-06 09:59

What is the best way to remove all text in a string after a specific character? In my case "=" and after another character in my case a ,, but keep th

相关标签:
5条回答
  • 2020-12-06 10:28

    This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.

    To keep the text which falls between the equal sign and the comma:

    -replace "^.*?=(.*?),.*?$",'$1'
    

    This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.

    0 讨论(0)
  • 2020-12-06 10:29

    I referenced @benjamin-hubbard 's answer above to parse the output of dnscmd for A records, and generate a PHP "dictionary"/key-value pairs of IPs and Hostnames. I strung multiple -replace args together to replace text with nothing or tab to format the data for the PHP file.

    $DnsDataClean = $DnsData `
        -match "^[a-zA-Z0-9].+\sA\s.+" `
        -replace "172\.30\.","`$P." `
        -replace "\[.*\] " `
        -replace "\s[0-9]+\sA\s","`t"
    
    $DnsDataTable = ( $DnsDataClean | `
        ForEach-Object { 
            $HostName = ($_ -split "\t")[0] ; 
            $IpAddress = ($_ -split "\t")[1] ; 
            "`t`"$IpAddress`"`t=>`t'$HostName', `n" ;
        } | sort ) + "`t`"`$P.255.255`"`t=>`t'None'"
    
    "<?php
    `$P = '10.213';
    `$IpHostArr = [`n`n$DnsDataTable`n];
    
    ?>" | Out-File -Encoding ASCII -FilePath IpHostLookups.php
    
    Get-Content IpHostLookups.php
    
    0 讨论(0)
  • 2020-12-06 10:30
    $a="some text =keep this,but not this"
    $a.split('=')[1].split(',')[0]
    

    returns

    keep this
    
    0 讨论(0)
  • 2020-12-06 10:32

    Another way to do this is with operator -replace.

    $TestString = "test=keep this, but not this."
    
    $NewString = $TestString -replace ".*=" -replace ",.*"
    

    .*= means any number of characters up to and including an equals sign.

    ,.* means a comma followed by any number of characters.

    Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.

    0 讨论(0)
  • 2020-12-06 10:40

    This should do what you want:

    C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
    keep this
    
    0 讨论(0)
提交回复
热议问题