Home > Software engineering >  How do you move n characters that are between 2 words to the end of the line (inside of a multi-line
How do you move n characters that are between 2 words to the end of the line (inside of a multi-line

Time:11-07

The multi-line string always contains XY, followed by a few characters (not always the same amount of characters), followed by :thiSWORD:

The goal is to move these few characters that are in the middle to the end of the line

So, for example, this is the original string:

XY1239:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f
XY545:thiSWORD:b598944d1ba4c787e411800b8043559c
XY4239:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c6

In the end it would look like this:

XY:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f1239
XY:thiSWORD:b598944d1ba4c787e411800b8043559c545
XY:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c64239

I have tried something along the lines of

str.replace(/(\w{4})(\w{48})/g, '$2$1');

But that only moved 4 characters, so lines that had 3 or 5 characters between XY and :thiSWORD: were messed up.

CodePudding user response:

You can use 2 capture groups, and use those in the replacement:

XY(\d )(.*)
  • XY Match literally
  • (\d ) Capture 1 digits in group 1
  • (.*) Capture the rest of the line in group 2

See a regex demo.

[
  "XY1239:thiSWORD:a6b4ba21ba54f6bde411930b0d88432f",
  "XY545:thiSWORD:b598944d1ba4c787e411800b8043559c",
  "XY4239:thiSWORD:a6b4ba21ba54f6bde411930b0d8817c6"
].forEach(s => {
  console.log(s.replace(/XY(\d )(.*)/, "XY$2$1"))

})


Another variant using 1 or more word characters \w if there can also be word characters instead of only digits, matching 32 word chars instead of 48, word boundaries on the left and right and matching :thiSWORD:

\bXY(\w )(:thiSWORD:\w{32})\b

Regex demo

  • Related