Replace multiple dots in a string with a different character, but with the same amount

I have a line like the following "Blaa ... blup..blaaa ... blah."

Each part, where there is more than one point, must be replaced by "_", but it must have the same amount as the replaced characters.

The line should lead to: "Blah ___ blup__blaaa ___ blah."

Please note that the last point is not replaced because it has no other connected points.

I tried using the following regex approach in powershell, but I always get legnth from 2 for a match no matter where there are 3 or more points:

$string -replace '(.)\1+',("_"*'$&'.length)

Any ideas?

+4
source share
3 answers

\G anchor .

\.(?=\.)|\G(?!^)\.
  • \.(?=\.) , .
  • |\G(?!^)\. , ( )

. . regexstorm

+7

, , " ", . . Powershell .

:

((?=\.{2})|(?!^)\G)\.

_.

- regex .

enter image description here

:

  • ((?=\.{2})|(?!^)\G) - , 2 ( (?=\.{2})), ( (?!^)\G)
  • \. - .
+3

You can use the following template:

\.(?=\.)|(?<=\.)\.

And replace with _.

The template simply looks for either a period preceded by a period or a period followed by a period:

  • \.(?=\.) - corresponds to the period followed by the period
  • | - Or
  • (?<=\.)\. - Corresponds to the period preceded by the period

Watch the online demo.

+3
source

Source: https://habr.com/ru/post/1627804/


All Articles