N
N
neitri2018-07-04 19:38:52
PowerShell
neitri, 2018-07-04 19:38:52

Extra spaces when regex replaced in PowerShell?

There is a file in which values ​​are written through | . Looks like this

PARAM_ONE|1|N
PORT|1|502
PARAM_TWO|1|0

I need to change PORT|1|502 to PORT|1|500 For this I
use the expression (PORT\|\d+\|)(\d+) with the replacement $1 500
As a result, I get the string PORT|1| 500 in which a space appeared.
I am trying to make a replacement with such a team.
"PORT|1|502" -creplace "(PORT\|\d+\|)(\d+)",'$1 500'

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dodo512, 2018-07-05
@neitri

"PORT|1|502" -creplace "(PORT\|\d+\|)(\d+)", '${1}500'

"PORT|1|502" -creplace "(?<=PORT\|\d+\|)\d+", '500'

A
azarij, 2018-07-04
@azarij

a crutch of course, but it works. just need some unique delimiter and another replace run:
"PORT|1|502" -replace "(PORT\|\d+\|)(\d+)","`$1 500" -replace " "
or
"PORT |1|502" -replace "(PORT\|\d+\|)(\d+)","`$1zhopa500" -replace "zhopa"
UPD: replaced single quotes with double quotes and added back quote to $1
UPD: like this works:
$port="500"
"PORT|1|502" -replace "(PORT\|\d+)\|(\d+)","`$1|$port"

N
neitri, 2018-07-04
@neitri Автор вопроса

Получилось ещё вот так:
"PORT|1|502" -creplace "(PORT\|\d+)\|(\d+)",'$1|500'
Но это какой то костыль все равно.
Проблема в том что в строке замены нельзя написать $1500 т.к. аргументы нельзя разделить (цифры объединяются) Может можно как то переменную указать вместо второго аргумента $1$port но так переменную $port не видно.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question