Remove everything from string before given variable

Viewed 1541

I have a string some\string/with/**/special\chars\haha. In variable I hold chars string and I try to remove everything before and including chars so expected output would be \haha

I tried sth like:

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$temp -replace '(?s)^.*$tmp', ''

and

$temp -replace '(?s)^.*$([regex]::Escape($tmp))', ''

but the only thing that works is when I put the string directly into regex condition. Only this example gives expected output:

$temp -replace '(?s)^.*chars', ''

What am I doing wrong?

Edit.: I need to use variable in regex, because I iterate through multiple strings like this one and not always the part I want to remove has the same string (example: some\string/with/**/special\chars\haha -> \haha; C:\st/h/*/1234\asdf\x -> \x). So in conclusion I have a problem using variable in regex, not with the regex itself as that works as intended when I replace variable with string (as shown above)

2 Answers

Try

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$regex = '(?s)^.*' + $tmp
$temp -replace $regex, ''

Looks like it's because you are using single quotes in your regex instead of double quotes. This means that the variable $tpm isn't being used.

Here is what your code should look like:

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$temp -replace "(?s)^.*$tmp", ''

Your code was using $tmp instead of the actual value inside the $tmp variable.

Related