Find and replace text iteratively from a list

Suppose I have this text:

Donec sollicitudin ? malesuada. "Curabitur" arcu erat, accumsan
id imperdiet et, porttitor at sem. Quisque velit nisi, ? ut
lacinia in, ? id enim. Proin eget tortor risus.

and I have these texts in the list:

["apple", "banana", "cherry"]

How can I replace every occurrence? with every text in the list? Expected Result:

Donec sollicitudin apple malesuada. "Curabitur" arcu erat, accumsan
id imperdiet et, porttitor at sem. Quisque velit nisi, banana ut
lacinia in, cherry id enim. Proin eget tortor risus.

Is it possible to use notepad ++ to achieve something similar for longer text and a list? Or are there other technologies that I can use?

+4
source share
4 answers

This Python script will do the job. If there are more ?substitutions in the list , this will leave them as ?.

import re

replacements = ["apple", "banana", "cherry"]
lines = ""

with open("file.txt") as file:
    lines = file.read()

def replace(m):
    if not replacements:
        return "?"

    return replacements.pop(0)

lines = re.sub(r"\?", replace, lines)

with open("file.txt", "w") as file:
    file.write(lines)

Admittedly, there are better ways to do this, such as not loading the entire file into a string.

0
source

You can try to make three regular expressions in a row:

To find:

([^?]*)?\?(.*)

Replace:

$1apple$2

, ([^?]*)?\? . ? .

.

0

You can use the regex below:

\?(?!(.|\s)*\?(.|\s)*)

He will select last ? and give you his index. After that, you can replace it with the last element of your array (it would be better to create a stack containing ["apple", "banana", "cherry"]so that the method stack.popalways gives you the last element.)

0
source

In Perl:

$text =~ s{\?}{shift @fruits}eg;  # Consumes @fruits array

or

my $i = 0;
$text =~ s{\?}{$fruits[$i++]}g;   # Preserves @fruits

To loop over @fruits(if the number ?exceeds the number of fruits):

my $i = 0;
$text =~ s{\?}{$fruits[ $i++ % @fruits ]}g;
0
source

Source: https://habr.com/ru/post/1686785/


All Articles