3

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)

3
  • The PS tag is not valid on this post. I'm confused by your question, you're technically doing nothing wrong since you have the expected output with the final command Commented Jun 26, 2019 at 9:47
  • I need to use variable in regex. When I use variable output of the command is the same as input. On the other hand when I use string like in example in question I receive correct output. So I need help with using the variable in regex. I'll further clarify the question Commented Jun 26, 2019 at 9:55
  • 1
    The variable $tmp is not being replaced here because single-quoted strings are not subject to string interpolation: '(?s)^.*$tmp'. Replacing the quotes will enable this feature, but I'm not sure your regex will then give the result you're looking for. Commented Jun 26, 2019 at 10:01

2 Answers 2

3

Try

$temp = "some\string/with/**/special\chars\haha"
$tmp="chars"
$regex = '(?s)^.*' + $tmp
$temp -replace $regex, ''
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you for explanation. Your answer together with commend of @boxdog explained what I did wrong. As that precisely addresses my question this is accepted answer. **For future readers - answer of Justin Cooksey is working too!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.