0

I am trying to use -replace statement to do the conditional replacement in PowerShell.

Below is my reproduceable example:

$content = @'
a<a
a>a
a'a
a&quote;a
a&a
johnson&johnson
J&J
R&D
P&AB
M&ABC
O&ABCD
B&SS-IHC
S&B
GC&E
M&G
P&D
'@

I want to replace all the & with &, but if the string is ended with ; then don't replace. The result would be:

a<a
a>a
a'a
a&quote;a
johnson&johnson
J&J
R&D
P&AB
M&ABC
O&ABCD
B&SS-IHC
S&B
GC&E
M&G
P&D

So far I can only come up with $modifiedContent = $content -replace '(\w)&(\w*)[^;]|$' , '$1&$2' and I am getting nowhere. How can I add a condition correctly that will do the trick?

Thanks in advance.

2
  • Try -replace '\b&(?!\w+;)(?=\w)', '&' Commented Nov 18, 2020 at 10:43
  • You can match & not followed by any of the alternatives &(?!lt|gt|amp|quote|apos) regex101.com/r/AYlNsW/1 Commented Nov 18, 2020 at 10:43

3 Answers 3

2

You may use

\b&\b(?!\w+;)

Replace with &. See a regex demo.

Details

  • \b - a word char is required immediately to the left of the current location
  • & - a & char
  • \b - a word char is required immediately to the right of the current location
  • (?!\w+;) - immediately to the right, there should be no 1+ word chars and a ;.
Sign up to request clarification or add additional context in comments.

Comments

1

You could also specify what you don't want to match as it seems you want to exclude certain special entities.

Use a negative lookahead with an alternation to assert what is at the right is not any of the listed alternatives followed by a ; and replace with &

&(?!(?:lt|gt|amp|quote|apos);)

Explanation

  • & Match literally
  • (?! Negative lookahead
    • (?:lt|gt|amp|quote|apos); Match any of the listed followed by ;
  • ) Close lookahead

Regex demo

Comments

1
([regex]"(\S*)(&)(?!\S*;)(\S*)").Replace($content, '$1&$3')

Comments

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.