Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace string to the left of value and to the right of quote character

I have a text file content.txt:

Some other text 1
"one" : "Text To Replace1:/Text To Stay.133" 
Some other text 2
"five" : "Text To Change2:/Another Text To Stay.50" 
Some other text 5  

I came up with the following script:

$SRCFile = "K:\content.txt"
$DSTFile = "K:\result.txt"
$Text2Replace = "YabaDaba.du:/"

get-content $SRCFile |
ForEach-Object { $_ -replace ".*:\/", $Text2Replace } | Out-File $DSTFile

It works almost okay, but it selects the entire line to the left of the ":/" string. I want it only to select the text to the previous quotation mark (excluding it):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired selection

What regex value should I use to point the above script to select only the text up to previous quotation mark? I’ve been trying Regex101.com, especially LookBehind, but I couldn’t come up with any idea.

>Solution :

(?<=.+: ").*:\/ might do what you’re after. In this case you can also read the file as single multi-line string (hence the use of -Raw in the code) and the use of the (?m) flag (Multiline mode).

See https://regex101.com/r/3CXaOI/1 for details.

$Text2Replace = "YabaDaba.du:/"

(Get-Content $SRCFile -Raw) -replace '(?m)(?<=.+: ").*:\/', $Text2Replace |
    Out-File $DSTFile
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading