2

I would like replace ? in

"EquipmentInfo["?"] = "<iframe src='http://bing.fr'></iframe>";"

by a variable.

I tried this:

(get-content C:\word.txt) -replace '?', '$obj' | Set-Content C:\word.txt

0

2 Answers 2

3

I would use a positive lookbehind to ensure you find the right question mark. Also you have to use double quote on your replacement since you want to replace a variable:

(get-content C:\word.txt -raw) -replace '(?<=EquipmentInfo\[")\?', "$obj" | Set-Content C:\word.txt

Regex used:

(?<=EquipmentInfo\[")\?

Regular expression visualization

Sign up to request clarification or add additional context in comments.

1 Comment

++ for a solid solution: also worth mentioning that a simple variable reference needs no quotes at all.
2

This answer explains the original problem.
jisaak's helpful answer provides a comprehensive solution.

The -replace operator takes a regular expression as the first operand on the RHS, in which ? is a so-called metacharacter with special meaning.

Thus, to use a literal ?, you must escape it, using \:

(get-content C:\word.txt) -replace '\?', $obj   

Note: Do not use '...' around $obj, unless you want literal string $obj; generally, to reference variables inside strings you must use "...", but that's not necessary here.

A simple example with a literal:

'Right?' -replace '\?', '!' # -> 'Right!'

4 Comments

I try this too but powershell don't agree + (get-content C:\word.txt) -replace '?', '$obj' ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation : (?:String) [], RuntimeException + FullyQualifiedErrorId : InvalidRegularExpression
Then the problem must lie elsewhere - see my example. Please add an MCVE (Minimal, Complete, and Verifiable Example) directly to your question.
Your solution is valid too, thus upvoted. Just wanted to add a more save regex for the replacement. Don't know why he isn't able to run it...
@jisaak I appreciate it, and I appreciate your comprehensive solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.