ingredient_15939
ingredient_15939

Reputation: 3134

JS Regex: How to replace lines of text within a specific area?

Doing some text manipulation, and I need a regex which will find each indented line within the first group, but not the second group, of the text below:

First group of lines are below:
- line 1
- line 2
- line 3

Second group of lines are below:
- line 1
- line 2
- line 3

For example, I want to insert an "A" in front of the numbers, but only in the first group. So I get:

- line A1
- line A2
- line A3

But again only in the first group, even though the second group's lines are identical. Simply doing .replace(/^(- \w+ )(\d)/,'\1A\2' will perform the replace on all lines, but I don't know how to restrict it to only the first group.

Is Javascript (or any other flavour) regex able to do that? That is, operate on a set of consecutive matches only if the set is preceded by a "defining" match?

Upvotes: 0

Views: 54

Answers (1)

collapsar
collapsar

Reputation: 17238

Extract the portion of text amenable to replacements first:

 var a_parts
   , s_orig
   , s_final
   , s_sep
   ;

 s_orig = <from_whatever_source>;
 s_sep  = "Second group of lines are below:"; 
 a_parts = s_orig.split(s_sep);
     // Substitute on a_parts[0], leave a_parts[1] untouched.
 s_final =
     a_parts[0].replace(/^(- \w+ )(\d)(.*)/g,'\1A\2')
   + s_sep
   + a_parts[1]
 ;

The method generalizes in a straightforward way to more sections that are to be treated differently. Note that the argument to .split may be a regex so you can specify an alternation of section separators.

That somewhat resembles the concept of a 'defining match' introducing (in general: delimiting) the relevant part of the original string.

Upvotes: 1

Related Questions