Java 字符串变量替换 |
您所在的位置:网站首页 › java字符串代替 › Java 字符串变量替换 |
0. 概述
处理字符串变量替换,可以用占位符替换的方式,如 Apache Commons Text、模板替换的方式,如 FreeMarker、正则替换的方式等。 下面介绍几种常见的,不用额外引入 jar 包的方式。 1. java.lang.String String str = String.format("Hello %s, You've logged in %d times.", "archer", 10); System.out.println(str);占位符描述参考:Class Formatter 2. java.text.MessageFormat String str = MessageFormat.format("Hello {0}, You''ve logged in {1} times.", "archer", 10); System.out.println(str);备注: 要输出单引号,需要在 pattern 字符串中使用两个单引号 要输出左花括号,需要在 pattern 字符串中用成对单引号包围左花括号 pattern 字符串中使用一个单引号,单引号会被省略且后面的占位符也会失效参考:Class MessageFormat 3. SpEL Map params = ImmutableMap.of("name", "archer", "times", "10"); ExpressionParser parser = new SpelExpressionParser(); TemplateParserContext parserContext = new TemplateParserContext(); String str = parser.parseExpression("Hello #{[name]}, You've logged in #{[times]} times.", parserContext).getValue(params, String.class); System.out.println(str);参考:Spring Expression Language (SpEL) 4. @Slf4j 中 log.info 使用占位符(虽不属于该主题,但方式较类似,所以也放在了文中) log.info("Hello {}, You've logged in {} times.", "archer", 10); |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |