{ }codelper
finding textreplacing textsubstringsP0101

Template filler

The first line gives a template string T. The second line gives the number of definitions n, and each of the next n lines gives "name=value". The value is every character after the first "=" on that line, and it may be empty. If a name is defined more than once, only the last definition is used. Print T on one line with every placeholder {name} replaced by that name's value. A placeholder whose name is not defined stays as {name}. Inserted values are never scanned again: print them as they are, even if they contain {name}, $ or \.

Input
T has 1 to 1000 characters and does not start or end with a space.
In T, { and } are used only for placeholders, and a placeholder is { + 1 to 10 lowercase English letters + }.
0 ≤ n ≤ 50.
Names are 1 to 10 lowercase English letters.
Values are 0 to 30 printable ASCII characters (they may contain {, }, =, $ and \) and do not start or end with a space
Output
T with its placeholders replaced, on one line
Example 1 · stdin
Dear {name}, your code is {code}. {name}, see {link}.
3
name=Jun
code={name}$1
name=Mina
stdout
Dear Mina, your code is {name}$1. Mina, see {link}.
Example 2 · stdin
{first} and {second}
2
first={second}
second=B
stdout
{second} and B
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The key is to scan the template left to right exactly once.
Calling replace for each name in turn replaces the {second} inside a value inserted earlier (the second example).
Searching again from the replaced position is the same mistake, and if a value contains its own name (a=<{a}>) it never ends.
There are two single-pass ways.
One is to pass a replacement function with the regex \{([a-z]+)\}: Python re.sub(pat, fn, t), JS/TS t.replace(/…/g, fn), C# Regex.Replace(t, pat, m => …), Java matcher.replaceAll(r -> …).
The other is to find { (find, indexOf, strchr) and move forward, copying the slice before it.
C, C++ and Craykon do that.
Three more traps.
In JS, passing a string as in t.replace("{a}", v) replaces only the first match; use replaceAll or a /g regex to replace all.
In JS, a replacement passed as a string instead of a function gives $&, $1 and $$ special meanings, and a string replacement in Python re.sub reads \1 as a group.
Java reads $1 and \ even in the string returned by a function passed to replaceAll, so wrap it in Matcher.quoteReplacement.
A value returned by a C# MatchEvaluator is inserted as is.
Craykon finds with rest.IndexOf("{") and slices with rest.Substring(0, open).
IndexOf takes no start position, so it searches again in rest, with the processed front cut off.

Pythonmain.py · 17 lines
import re template = input()n = int(input())values = {}for _ in range(n):    key, value = input().split("=", 1)    values[key] = value  # 같은 이름이 또 나오면 나중 값이 이긴다  def fill(m):    # 정의된 이름이면 값을, 아니면 {이름} 그대로    return values.get(m.group(1), m.group(0))  # 바꾸기 함수를 넘기면 값 안의 {..}나 \1을 다시 읽지 않는다print(re.sub(r"\{([a-z]+)\}", fill, template))
JavaScriptmain.js · 11 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const template = lines[0];const n = Number(lines[1]);const values = new Map();for (let i = 2; i < 2 + n; i++) {  const eq = lines[i].indexOf("=");  values.set(lines[i].slice(0, eq), lines[i].slice(eq + 1));}// 함수를 넘기면 돌려준 문자열을 그대로 넣는다($&·$1을 읽지 않음)const out = template.replace(/\{([a-z]+)\}/g, (whole, key) => (values.has(key) ? values.get(key) : whole));console.log(out);
TypeScriptmain.ts · 12 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const template: string = lines[0];const n: number = Number(lines[1]);const values = new Map<string, string>();for (let i = 2; i < 2 + n; i++) {  const eq: number = lines[i].indexOf("=");  values.set(lines[i].slice(0, eq), lines[i].slice(eq + 1));}// 함수를 넘기면 돌려준 문자열을 그대로 넣는다($&·$1을 읽지 않음)const out: string = template.replace(/\{([a-z]+)\}/g, (whole: string, key: string): string => values.get(key) ?? whole);console.log(out);
JavaMain.java · 25 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        String template = in.readLine();        int n = Integer.parseInt(in.readLine().trim());        Map<String, String> values = new HashMap<>();        for (int i = 0; i < n; i++) {            String line = in.readLine();            int eq = line.indexOf('=');            values.put(line.substring(0, eq), line.substring(eq + 1));        }        Matcher m = Pattern.compile("\\{([a-z]+)\\}").matcher(template);        // 돌려준 문자열 안의 $와 \는 그룹 참조로 읽히니 quoteReplacement로 감싼다        String out = m.replaceAll(r -> Matcher.quoteReplacement(values.getOrDefault(r.group(1), r.group())));        System.out.println(out);    }}
C#Main.cs · 23 lines
using System;using System.Collections.Generic;using System.Text.RegularExpressions; class Program{    static void Main()    {        string template = Console.ReadLine();        int n = int.Parse(Console.ReadLine());        var values = new Dictionary<string, string>();        for (int i = 0; i < n; i++)        {            string line = Console.ReadLine();            int eq = line.IndexOf('=');            values[line.Substring(0, eq)] = line.Substring(eq + 1);        }        // MatchEvaluator가 돌려준 문자열은 그대로 들어간다($ 해석 없음)        string output = Regex.Replace(template, @"\{([a-z]+)\}",            m => values.TryGetValue(m.Groups[1].Value, out string v) ? v : m.Value);        Console.WriteLine(output);    }}
C++main.cpp · 27 lines
#include <iostream>#include <string>#include <unordered_map> int main() {    std::string t, line;    std::getline(std::cin, t);    std::getline(std::cin, line);    int n = std::stoi(line);    std::unordered_map<std::string, std::string> values;    for (int i = 0; i < n; i++) {        std::getline(std::cin, line);        auto eq = line.find('=');        values[line.substr(0, eq)] = line.substr(eq + 1);    }    std::string out;    std::size_t pos = 0;    for (auto open = t.find('{'); open != std::string::npos; open = t.find('{', pos)) {        auto close = t.find('}', open);        out += t.substr(pos, open - pos);        auto it = values.find(t.substr(open + 1, close - open - 1));        out += it != values.end() ? it->second : t.substr(open, close - open + 1);        pos = close + 1; // 넣은 값은 다시 보지 않고, 템플릿의 그다음부터 찾는다    }    out += t.substr(pos);    std::cout << out << '\n';}
Cmain.c · 46 lines
#include <stdio.h>#include <string.h> static char keys[50][11], vals[50][32];static int count = 0; /* 이름이 정의돼 있으면 그 값, 없으면 NULL. 나중에 넣은 것이 이기도록 뒤에서부터 찾는다 */static const char *lookup(const char *key) {    for (int i = count - 1; i >= 0; i--)        if (strcmp(keys[i], key) == 0) return vals[i];    return NULL;} int main(void) {    static char t[1100], line[64];    int n;    fgets(t, sizeof t, stdin);    t[strcspn(t, "\n")] = '\0';    fgets(line, sizeof line, stdin);    sscanf(line, "%d", &n);    for (int i = 0; i < n; i++) {        fgets(line, sizeof line, stdin);        line[strcspn(line, "\n")] = '\0';        char *eq = strchr(line, '=');        *eq = '\0';        strcpy(keys[count], line);        strcpy(vals[count], eq + 1);        count++;    }    const char *p = t;    const char *open;    while ((open = strchr(p, '{')) != NULL) {        const char *close = strchr(open, '}');        fwrite(p, 1, open - p, stdout);            /* { 앞까지 그대로 */        char key[16];        int len = (int)(close - open - 1);        memcpy(key, open + 1, len);        key[len] = '\0';        const char *v = lookup(key);        if (v) fputs(v, stdout);        else fwrite(open, 1, close - open + 1, stdout); /* 없는 이름은 {이름} 그대로 */        p = close + 1;    }    puts(p);    return 0;}
Craykonmain.cray · 31 lines
t = Console.ReadLine();n = Console.ReadLine().ToNumber();values = Dict();for (i = 0; i < n; i++){    line = Console.ReadLine();    eq = line.IndexOf("=");    values[line.Substring(0, eq)] = line.Substring(eq + 1);}out = "";rest = t;open = rest.IndexOf("{");while (open != -1){    close = rest.IndexOf("}");    key = rest.Substring(open + 1, close - open - 1);    out += rest.Substring(0, open);    if (values.Contains(key))    {        out += values[key];    }    else    {        out += rest.Substring(open, close - open + 1);    }    // 넣은 값은 다시 보지 않고, 템플릿의 남은 부분에서만 찾는다    rest = rest.Substring(close + 1);    open = rest.IndexOf("{");}out += rest;Console.WriteLine(out);