Welcome › Forums › General PowerShell Q&A › RegEx to replace value between quotes only
- This topic has 7 replies, 3 voices, and was last updated 2 weeks, 4 days ago by
Participant.
-
AuthorPosts
-
-
January 1, 2021 at 3:24 pm #283600
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),’?’
-
January 1, 2021 at 5:50 pm #283615
You could use a negative lookahead to match ‘!’ where ‘!’ is not at the end of the string:
PowerShell12PS E:\Temp> '"This is a test! Yes it is",!' -replace '!(?!$)','?'"This is a test? Yes it is",!-
This reply was modified 2 weeks, 5 days ago by
Matt Bloomfield. Reason: Code formatting
-
January 1, 2021 at 7:17 pm #283630
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.
-
This reply was modified 2 weeks, 5 days ago by
-
January 2, 2021 at 4:56 am #283669
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?
PowerShell1$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?
-
January 2, 2021 at 9:56 am #283702
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
-
January 2, 2021 at 12:09 pm #283726
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.
PowerShell12345678$csv = Import-CSV myCSV.csvforeach ($row in $csv) {$row.column1 = $row.column1 -replace '!(?!$)','?'$row | Export-Csv newCSV.csv -Append -NoClobber -NoTypeInformation}-
This reply was modified 2 weeks, 4 days ago by
Matt Bloomfield. Reason: Code formatting
-
This reply was modified 2 weeks, 4 days ago by
-
January 2, 2021 at 4:23 pm #283780
Thanks Matt, this works perfectly. Cheers.
-
-
January 2, 2021 at 5:49 am #283681
-
-
AuthorPosts
- You must be logged in to reply to this topic.