Zakaria Belghiti
Zakaria Belghiti

Reputation: 551

Regex get all text before a string

In this text I want to select all of it until this string :

IF EXIST %logfile% DEL %logfile%

How can I achieve this with a regex in Powershell?

Upvotes: 1

Views: 113

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

I want to achieve is to replace all the text before that string by another text

You do not actually need any regex here, as the string you want to use a trailing delimiter is a literal string. Just use .Substring():

$str.Substring($str.IndexOf("IF EXIST %logfile% DEL %logfile%"))

This will get you the whole string from the first "IF EXIST %logfile% DEL %logfile%".

Here is a demo:

$newtext = "This is a new beginning.`n`n"
$res = $newtext + $str.Substring($str.IndexOf("IF EXIST %logfile% DEL %logfile%"))

enter image description here

Upvotes: 2

user4317867
user4317867

Reputation: 2448

Try this

"How IF EXIST %logfile% DEL %logfile% long the pattern is repeated." -replace ('IF EXIST %logfile% DEL %logfile%','replaced by this text $file')

Upvotes: 0

Related Questions