Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell RegExp

I have a string with commas where I want to replace the commas with tildes except where there is a number each side of the comma. Please can someone explain why this works:

$Str = "abc,12345,67,89,xyz,5,f"
$Str -replace '(?<!\d),', '~' -replace ',(?!\d)', '~'

but this does not work:

$Str = "abc,12345,67,89,xyz,5,f"
$Str -replace '(?<!\d),(?!\d)', '~'
like image 417
Aardvark Avatar asked Feb 25 '26 04:02

Aardvark


1 Answers

You need to use

$Str -replace '(?<!\d),|,(?!\d)', '~'

See the regex demo.

The (?<!\d),(?!\d) regex matches any comma that does not have a digit BOTH on the left AND on the right (so, you would get a match if you had a string like abc,xyd), you need to match any comma that has no digit EITHER on the left OR on the right (so as to find a match in abc,5 and in 5,abc).

The regex details are

  • (?<!\d), - a comma that has no digit immediately on the left
  • | - or
  • ,(?!\d) - a comma that has no digit immediately on the right.
like image 140
Wiktor Stribiżew Avatar answered Feb 27 '26 21:02

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!