RegEx to replace value between quotes only

Hello everyone, I have an expression below and I just want to replace the ! inside the " " with ?.

“This is a test! Yes it is”,!

It should say this after replacement:

“This is a test? Yes it is”,!

What is the Regex so I can use it in the below Powershell code? Thanks in advance.

$Content = $Content -replace [Regex]::Escape($string),’?’

You could use a negative lookahead to match ‘!’ where ‘!’ is not at the end of the string:

PS E:\Temp> '"This is a test! Yes it is",!' -replace '!(?!$)','?'
"This is a test? Yes it is",!

 

Thanks Matt, but my actually line does not always end with !. Also, I have a csv file with many such lines that I need to sort through. Any other suggestions? Thanks.

 

It doesn’t matter if the string ends with a ! or not, the idea of the regex is to find all of the exclamation marks that aren’t at the end of the string, which it does.

Are you using this code in a loop or just as posted?

$Content = $Content -replace [Regex]::Escape($string),’?’

If you have multiple strings you’ll need to check each one. You can’t just read the file into $content and do a single replace. Can you provide a few example rows of the CSV for testing?

gmx.de login

Hello Matt, I have csv file with many lines like below. Each line has a only one pair of quotes (ie " ") with ! inside that I only want to change to ?.

 

“This is a test! Yes it is”,!

“abc!def it is”,!,0,0,:0

“firstname!lastname,",xx,xx,!,343

 

I am trying to modify below code to achieve my goal but needed some assistance :). Thanks.

(Get-Content $csvfile) -replace ‘!’, ‘?’ | Set-Content $csvfile2

Is the text in quotes always in the same column? Do you have column names?

I would use Import-CSV and just work on the column with the quotes.

$csv = Import-CSV myCSV.csv

foreach ($row in $csv) {

    $row.column1 = $row.column1 -replace '!(?!$)','?'
    $row | Export-Csv newCSV.csv -Append -NoClobber -NoTypeInformation

}

Thanks Matt, this works perfectly. Cheers.