Reputation: 119
In PowerShell when trying to replace
"Columnname1||colunnname2||kjhsadjhj|kjsad" -replace "[||]", "','"
above command is doing
"Columnname1','','colunnname2','','kjhsadjhj','kjsad"
but I'd like to replace the exact match like below
"Columnname1','colunnname2','kjhsadjhj|kjsad"
Upvotes: 2
Views: 223
Reputation:
Just in case your end result should be:
'Columnname1','colunnname2','kjhsadjhj|kjsad'
$string = '"Columnname1||colunnname2||kjhsadjhj|kjsad"'
$string
$String = $string -replace '^"|"$',"'" -replace '\|{2}',"','"
$string
Sample output:
"Columnname1||colunnname2||kjhsadjhj|kjsad"
'Columnname1','colunnname2','kjhsadjhj|kjsad'
Upvotes: 0
Reputation: 200273
Your code doesn't do what you want because your search pattern defines a character class. Square brackets in a regular expression will match exactly one occurrence of any of the enclosed characters, even if you specify a character multiple times. [||]
will thus match exatly one |
character.
Since you apparently don't actually want to use a regular expression match I'd recommend doing a normal string replacement via the Replace()
method rather than a regular expression replacement via the -replace
operator:
"Columnname1||colunnname2||kjhsadjhj|kjsad".Replace('||', "','")
If you want to stick with a regular expression replacement you must specify two literal |
characters, either by escaping them, as PetSerAl suggested
"Columnname1||colunnname2||kjhsadjhj|kjsad" -replace '\|\|', "','"
or by putting each of them in its own character class
"Columnname1||colunnname2||kjhsadjhj|kjsad" -replace '[|][|]', "','"
Upvotes: 3
Reputation: 174485
The regex pattern [||]
means "1 of |
or one of |
"
Change it to \|{2}
to match two consecutive pipes:
"Columnname1||colunnname2||kjhsadjhj|kjsad" -replace "\|{2}", "','"
Upvotes: 1