I have a string like this:
"Item 1","Item 2"
I would like to replace it so that it looks like this, using a powershell script:
Item 1{tab character}Item 2
I have this:
$text = '"Item 1","Item 2"'
$expr1 = '"([^"]+?)","([^"]+?)"'
$expr2 = "$1\t$2"
$line = [System.Text.RegularExpressions.Regex]::Replace($text, $expr1, $expr2);
but it doesn't work.
As an aside, is there a definitive reference for how to deal with escaping quotes and special characters in Powershell? I find it very confusing indeed.
.
.
EDIT:
The reason I want to do this is so that I can wrap this up in a parameterised script and call it using parameters. The script (regex-rs.ps1) is like this:
param
(
[string] $text,
[string] $inputPattern,
[string] $replacePattern
)
function Main()
{
$text2 = [System.Text.RegularExpressions.Regex]::Replace($text, $inputPattern, $replacePattern);
[System.Console]::WriteLine($text2);
}
Main;
Unfortunately, when I call the script like this:
powershell .\regex-rs.ps1 '"Text1","Text2"' '`"([^`"]+?)`",`"([^`"]+?)`"' '`$1`t`$2'
It outputs:
Text1,Text2
In other words, no tab. What am I doing wrong?
.
.
FURTHER EDIT IN RESPONSE TO NICK'S ANSWER BELOW: (I have to put this here, because the comment formatting in StackOverflow messes around with backticks)
I replaced the single quotes with double quotes in my powershell call, like so:
powershell .\regex-rs.ps1 ""Text1","Text2"" "`"([^`"]+?)`",`"([^`"]+?)`"" "`$1`t`$2"
But I got this error:
Missing ] at end of type token.
Any further ideas?
.
FINAL EDIT: This is the call to the script that fixed the issue (have to post as an image, because it's so powerful that it's defied StackOverflow's formatting, even here): .
$line = [System.RegularExpressions.Text]::Replace($text, $expr1, $expr2);
be$line = [System.Text.RegularExpressions.Regex]::Replace($text, $expr1, $expr2);
? – Nick Dec 21 '11 at 20:35