简体   繁体   English

JS Regex:如何在特定区域内替换文本行?

[英]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 . 例如,我想在数字前插入“ A”,但只能在第一组中 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. 简单地执行.replace(/^(- \\w+ )(\\d)/,'\\1A\\2'将在所有行上执行替换,但是我不知道如何将其限制为仅第一组。

Is Javascript (or any other flavour) regex able to do that? Javascript(或其他任何风味)正则表达式能够做到这一点吗? That is, operate on a set of consecutive matches only if the set is preceded by a "defining" match ? 也就是说, 仅在连续匹配的集合前面有“定义”匹配时才进行操作?

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. 请注意, .split的参数可能是正则表达式,因此您可以指定节分隔符的替代形式。

That somewhat resembles the concept of a 'defining match' introducing (in general: delimiting) the relevant part of the original string. 这有点类似于“定义匹配”的概念,引入(通常是:定界)原始字符串的相关部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM