输入以下数据:

图案:anyValue{variable1}otherValue{variable2}lastValue

值:anyValuehellootherValueworldlastValue

预期此输出

variable1: hello
variable2: world

我可以有任何带大括号的变量吗, 我想要一个使用正则表达式的例子,用Java或其他语言实现,

推荐答案

您可以在Java中使用以下代码:


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

public class Main {
    public static void main(String[] args) {
        String pattern= "anyvalue{variable1}anyvalue{variable2}anyvalue{var3}";
        String input = "anyvaluehelloanyvalueworldanyvaluesomething";

        // Convert the pattern into a regular expression
        String regex = pattern.replaceAll("\\{(.+?)\\}", "(?<$1>.*)");

        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(input);
        
        if (m.find()) {
            // Get the names of the capture groups from the pattern
            Pattern groupNamesPattern = Pattern.compile("\\(\\?<(.+?)>");
            Matcher groupNamesMatcher = groupNamesPattern.matcher(regex);
            
            // Print all the variables that were found
            while (groupNamesMatcher.find()) {
                String variableName = groupNamesMatcher.group(1);
                String variableValue = m.group(variableName);
                System.out.println(variableName + ": " + variableValue);
            }
        } else {
            System.out.println("No match found.");
        }
    }
}

我基本上是将您的模式转换为模式中任何{VARIABLE_NAME}的命名组.据我所知,没有简单的方法来获得组的名称,所以您需要第二个正则表达式来获得这些名称作为您的输出.

然而,似乎有一些替代方案可以找到指定的组.如果你想寻找其他 Select ,你可以关注this thread,以找到这些组的名称.

Java相关问答推荐

当一个链表中间有一个循环时,它的松散部分会发生什么?

在Java中测试DAO方法:假实现与内存数据库

Javascript在边界中心调整ImageView大小

即使我正在使用并发方法,使用Javascript的应用程序也会继续冻结'

AlarmManager没有在正确的时间发送alert

Spring Boot@Cachebale批注未按预期工作

Spring Boot 3.2.2中的@Inject和@Resource Remove

解释左移在Java中的工作原理

用户填充的数组列表永不结束循环

尽管通过中断请求线程死亡,但线程仍将继续存在

在Java 15应用程序中运行Java脚本和Python代码

由于在生成器模式中使用泛型,lambda表达式中的返回类型错误

在实例化中指定泛型类型与不指定泛型类型之间的区别

持续时间--为什么在秒为负数的情况下还要做额外的工作?

获取所有可以处理Invent.ACTION_MEDIA_BUTTON Android 13 API33的Android包

无法在IntStream上应用Collectors.groupingBy

如何使用Java ZoneID的区域设置?

";home/runner/work/中没有文件...匹配到[**/pom.xml];Maven项目的构建过程中出现错误

可以';不要在Intellij IDEA中使用最新的Java版本(JDK 21)

Java 8 中 ByteBuffer 和 BitSet 的奇怪行为