[string] PowerShell to remove text from a string

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 the text between?

Sample input

=keep this,

This question is related to string powershell

The answer is


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

$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]

returns

keep this

This should do what you want:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this

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.