You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java提取字符串中${}内变量的实现代码求助

Java提取字符串中${}包裹的变量

提取字符串里所有被${}包裹的变量,用正则表达式结合Java的Pattern和Matcher类是最直接高效的方案,以下是具体实现:

完整代码

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

public class VariableExtractor {
    public static List<String> extractVariables(String input) {
        // 正则规则:匹配${}格式,捕获{}内的变量内容
        String regex = "\\$\\{([^}]+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        List<String> variables = new ArrayList<>();
        // 遍历所有匹配结果
        while (matcher.find()) {
            // group(1)获取第一个捕获组的内容,即${}里的变量名
            variables.add(matcher.group(1));
        }
        return variables;
    }

    public static void main(String[] args) {
        // 测试示例输入
        String input = "This is a${VARIABLE1} sample string ${VARIABLE2} to process data ${VARIABLE3}";
        List<String> variables = extractVariables(input);
        
        // 打印提取结果
        System.out.println("提取到的变量:");
        for (String var : variables) {
            System.out.println(var);
        }
    }
}

代码解析

  • 正则表达式说明:\\$\\{([^}]+)\\}
    • \\$:匹配字符$(正则中$是特殊字符,需转义)
    • \\{:匹配字符{(同样需转义)
    • ([^}]+):捕获组,匹配除}外的任意字符([^}]表示非}的字符,+表示至少出现一次),这就是我们要提取的变量名
    • \\}:匹配字符}
  • 核心逻辑:通过matcher.find()循环查找所有符合格式的变量,每次用matcher.group(1)取出捕获到的变量名,存入列表
  • 测试输出:运行代码后会输出:
    提取到的变量:
    VARIABLE1
    VARIABLE2
    VARIABLE3
    

边界情况处理提示

  • 若要过滤空的${}(如test${}abc),可以在添加变量前判断:if (!matcher.group(1).isEmpty())
  • 若遇到嵌套的${}(如${VAR${SUB}}),上述正则会提取VAR${SUB,这类场景需要调整正则或用递归解析(但业务中嵌套情况极少)

内容的提问来源于stack exchange,提问作者Praveen Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:05:38