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)', '~'
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With