Home > other >  PowerShell replace text in string after certain expression
PowerShell replace text in string after certain expression

Time:10-08

I am trying to replace everything in a string after a certain expression is found: In this case ",=dc".

Im kinda new to PowerShell so would appreciate any help. My code only replaces any ",=dc" but not what is behind that

$array  = @()
$array  = "vu=doc,vu=noc,dc=zet,dc=zez"
$array  = "vu=doc,vu=nud,dc=gut,dc=zrt"
$array  = "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

foreach ($value in $array){
$arraytype -replace "(?<=(,=dc)).*"
}

I want to only get back the "vu=doc,vu=noc"-part. Everything after the first ",=dc" should be deleted.

CodePudding user response:

You can use IndexOf method to find the position of the string and use Substring method to slice the string up to that position.

$array = @()
$array  = "vu=doc,vu=noc,dc=zet,dc=zez"
$array  = "vu=doc,vu=nud,dc=gut,dc=zrt"
$array  = "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

foreach ($value in $array){
    $index = $value.IndexOf(",dc=")
    if($index -eq -1) {
        Write-Output $value
    } else {
        Write-Output $value.Substring(0, $index)
    }
}

Note: I think you have a typo in the first line($array = @())

CodePudding user response:

It's easier to use an indexed loop if you want the values in the array updated. Also, You can define an array simply by using a comma between the elements. Avoid concatenating with = as this means every time the entire array needs to be recreated in memory, which is both time and memory consuming.

Try

$array = "vu=doc,vu=noc,dc=zet,dc=zez",
         "vu=doc,vu=nud,dc=gut,dc=zrt",
         "vu=doc,vu=nud,vu=dit,dc=gut,dc=zrt,dc=opt"

for ($i = 0; $i -lt $array.Count; $i  ) {
    $array[$i] = ($array[$i] -replace 'dc=[^,] ,?').TrimEnd(",")
}

$array

Result:

vu=doc,vu=noc
vu=doc,vu=nud
vu=doc,vu=nud,vu=dit

Regex details:

dc=       Match the character string “dc=” literally (case insensitive)
[^,]      Match any character that is NOT a “,”
          Between one and unlimited times, as many times as possible, giving back as needed (greedy)
,         Match the character “,” literally
   ?      Between zero and one times, as many times as possible, giving back as needed (greedy)
  • Related