在 Java 中搜索 {{ 和 }} 之间的关键字的正则表达式

Regex to Search keywords between {{ and }} in Java

在 Java 中搜索 {{}} 之间的关键字的正则表达式是什么。

示例String = "kksdkjhsd {{one}} sdkjhsdjksd {{two}}" 我要output = ["one","two"];

我已经尝试过 Java Regex to get Data between curly brackets 中建议的方法。

它适用于单花括号,但我无法将其扩展为双花 ({{ }}) 花括号

您可以使用正则表达式:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static final String REGEX_START = Pattern.quote("{{");
    public static final String REGEX_END = Pattern.quote("}}");
    public static final Pattern PATTERN = Pattern.compile(REGEX_START + "(.*?)" + REGEX_END);

    public static void main(String[] args) {
        String input = "kksdkjhsd {{one}} sdkjhsdjksd {{two}}";
        List<String> keywords = new ArrayList<>();

        Matcher matcher = PATTERN.matcher(input);

        // Check for matches
        while (matcher.find()) {
            keywords.add(matcher.group(1)); // Group one is necessary because of the brackets in the pattern
        }

        // Print
        keywords.forEach(System.out::println);
    }
}

这将为您提供 {{}} 之间的所有内容,因此您将得到如下结果:

one
two

此代码应该符合您的要求:

Matcher m = Pattern.compile("\{\{([^\}]*)\}\}").matcher(word);

while (m.find()){
    System.out.println(m.group(1));
}

此正则表达式采用 {{ }} 中的所有文本,而不是 } 字符。此正则表达式不处理大小写限制,如 {{{}}},在本例中为 returns {,因为只有前两个 {{ 匹配。

如果您需要一个在范围内也匹配单个大括号的正则表达式,我们需要一个更复杂的解决方案。

另一件事,使用字符 class ([^\}]*) 使正则表达式比 (.*?) 更有效,因为它会在第一个不是闭合大括号的字符处停止搜索.

您可以试试正则表达式 [{][{].*?[}][}]。它使用不情愿的量词 *?,它匹配零个或多个字符,但以非贪婪的方式,因此,一旦它开始匹配 {{,它将在遇到的第一个 }} 处停止,而不是一直走到字符串的末尾并匹配 last }}.

作为一个有趣的小额外功能,它可以匹配 hey {{ how {} are }} you 之类的东西,并生成 how {} are 作为输出,而基于 [^}]* 的正则表达式不能。