Home > Mobile >  Copying header above using Javascript Regex Engine
Copying header above using Javascript Regex Engine

Time:06-21

Suppose you have the following multi-line string:

seq 1 description 1
val 1
val 2
val 3
seq 2 description 2
val 4
val 5
val 6

I would like to copy the the content of the lines beginning with "seq" to all the lines below, which begin with "val". I can do it just to the one line right below:

Regex: (^seq.*$)(\n)(val)
Substitution: $1$2$1 $3
Result:
seq 1 description 1
seq 1 description 1 val 1
val 2
val 3
seq 2 description 2
seq 2 description 2 val 4
val 5
val 6

But the result which I am looking for is the following:

seq 1 description 1 
seq 1 description 1 val 1
seq 1 description 1 val 2
seq 1 description 1 val 3
seq 2 description 2 
seq 2 description 2 val 4
seq 2 description 2 val 5
seq 2 description 2 val 6

Is it possible, only using Regex, or I do need a for loop?

CodePudding user response:

You could use a positive lookbehind, for example:

let text = `
seq 1 description 1
val 1
val 2
val 3
seq 2 description 2
val 4
val 5
val 6
`;

text = text.replace(/(?<=^(seq.*)[\s\S]*?)^val/gm, '$1 $&');

console.log(text);

The m flag is used to turn on 'multiline' mode so ^ matches the start of a line and not just the start of the string. The g flag is used to match globally, i.e. as many times as possible.

See regex101 for testing and further explanation.

Variation:

text = text.replace(/(?<=^(seq[^\r\n]*).*?)(?=^val)/gms, '$1 ');
  • Related