Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse and replace multiple variants using PowerShells regex

Parsing a text document using the code below matches every instance of '333', however I would like only the three examples below to be changed.

(Get-Content input.json) | ForEach-Object {
    $_ -replace '333', '666'
} | Set-Content output.json

This should change:

  • "se333" → "se666"
  • "SE333" → "SE666"
  • "333" → "666"

This should be left unchanged:

  • "1212333" → unchanged
  • "3331212" → unchanged
  • "333asda" → unchanged
  • "asd333" → unchanged

What is the PowerShell regex solution for this?

like image 609
Vidar Åsberg Avatar asked Apr 23 '26 17:04

Vidar Åsberg


1 Answers

You may use

(?i)(?<=\b(?:se)?)333\b

See the regex demo

Details

  • (?i) - case insensitive modifier
  • (?<=\b(?:se)?) - before 333 there must be a word boundary and anoptional substrin se
  • 333 - a literal substring
  • \b - a trailing word boundary.

Powershell test:

PS> $s = "se333 SE333 333 1212333 3331212 333asda asd333"
PS> $s -replace '(?i)(?<=\b(?:se)?)333\b', '666'
se666 SE666 666 1212333 3331212 333asda asd333
like image 191
Wiktor Stribiżew Avatar answered Apr 26 '26 07:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!