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

已知格式化后的fullName与teamPattern,如何还原原始teamName?

从格式化后的字符串还原原始teamName

要解决这个问题,核心思路是将原格式化模板(teamPattern)转换为正则表达式,通过捕获组提取出teamName。因为teamPattern可以任意设置,必须先转义其中的正则特殊字符,再把%s替换为捕获组,才能准确匹配并提取目标内容。

实现代码

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

public class TeamNameExtractor {

    public String generateFullName() {
        String teamPattern = "[MW3-%s]";
        String teamName = "apple";
        return teamPattern.formatted(teamName);
    }

    public String extractTeamName(String fullName, String teamPattern) {
        // 按%s分割模板,确保模板只有一个占位符
        String[] patternSegments = teamPattern.split("%s", -1);
        if (patternSegments.length != 2) {
            throw new IllegalArgumentException("模板必须包含且仅包含一个%s占位符");
        }

        // 转义模板前后段的正则特殊字符(如[]、.、*等)
        String escapedPrefix = Pattern.quote(patternSegments[0]);
        String escapedSuffix = Pattern.quote(patternSegments[1]);

        // 构建正则表达式,用捕获组匹配teamName
        String regex = escapedPrefix + "(.*)" + escapedSuffix;
        Pattern matchPattern = Pattern.compile(regex);
        Matcher matcher = matchPattern.matcher(fullName);

        if (matcher.matches()) {
            return matcher.group(1);
        } else {
            // 匹配失败时返回null,也可根据需求抛出异常
            return null;
        }
    }
}

代码说明

  1. 模板分割与校验:用%s分割teamPattern,确保模板只有一个占位符(因为生成fullName时只传入了一个teamName),否则直接抛出异常。
  2. 正则转义:使用Pattern.quote()转义模板前后段的正则特殊字符,避免这些字符被当作正则语法解析(比如原模板中的[和],在正则里是特殊符号,转义后会被当作普通文本处理)。
  3. 正则构建与匹配:将转义后的前后段用(.*)(贪婪捕获组)连接,生成正则表达式。用matcher.matches()确保整个fullName完全匹配模板,最后提取第一个捕获组的内容,就是原始的teamName。

注意事项

  • 如果teamName中包含与模板后缀完全相同的内容,还原结果依然正确——因为生成时确实是将整个teamName代入模板,正则会完整捕获对应的内容。
  • 若模板中没有%s或有多个%s,会直接抛出参数异常,因为这种模板无法通过单个teamName生成合法的fullName。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:35:55