Regex: заменить фразу только если НЕ предшествует слово - PullRequest
2 голосов
/ 05 февраля 2020

Я пытаюсь заменить некоторую фразу («мой термин») в текстовых файлах на perl командную строку. Эти файлы разделены на разделы, например:

section1
my term
nothing abc

section2
some text
my term
another text

section3
some text
my term

section4
some text
my term

Некоторые разделы могут не существовать. Чего я хочу добиться, так это заменить «мой термин» на «какой-то другой термин», но только если он есть в разделе1. Я попробовал некоторый синтаксис lookahead и lookbehinds, но не смог найти работающего решения (https://regex101.com/r/mfqay6/1)

Например, если я удаляю раздел 1, следующий код совпадает, тогда как Я не хочу этого:

(?!section2).*(my term)

Любая помощь там?

Ответы [ 2 ]

3 голосов
/ 05 февраля 2020

Простой вкладыш:

perl  -ane 's/my term/some other term/ if(/section1/ ... /section/);print' file.txt 

Выход:

section1
some other term
nothing abc

section2
some text
my term
another text

section3
some text
my term

section4
some text
my term
1 голос
/ 05 февраля 2020

Вот регулярное выражение:

((?:section1)(?:(?!my term)(?!^\s*$)[\d\D])+)(my term)

(                //start group 1
  (?:            //start non-capturing group (keeps it organized)
     section1    //match section1
  )              //end non-capturing group
  (?:            //start another non-capturing group
     (?!         //start negative lookahead
        my term  //don't match "my term"
     )           //end negative lookahead
     (?!         //start negative lookahead
        ^\s*$    //don't match an empty line
     )           //end negative lookahead
     [\d\D]      //match any character
  )+             //repeat this non-capturing group 1 or more times
)                //end group 1
(my term)        //match "my term" in group 2

А вот что заменить на:

$1my other term

$1            //everything up to "my term", including newline characters
my other term //the other term
...