String替换占位符
Posted muxi0407
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了String替换占位符相关的知识,希望对你有一定的参考价值。
/** * 依次替换占位符 * 例如: 姓名:{s},电话:{s},邮箱:{s} --> 姓名:小张,电话:18800000001,邮箱:abc@123.com * pattern = "\{s}"; * * @param input * @param pattern * @param texts * @param nullStr 不能为null * @return */ public static String appendReplacement(String input, String pattern, String[] texts, String nullStr) { // 从正则表达式实例中运行方法并查看其如何运行 Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(input); StringBuffer sb = new StringBuffer(); int i = 0; while (m.find()) { // 将匹配之前的字符串复制到sb,再将匹配结果替换掉,并追加到sb m.appendReplacement(sb, i < texts.length && texts[i] != null ? texts[i] : nullStr); i++; } m.appendTail(sb); return sb.toString(); }
Implements a non-terminal append-and-replace step. This method performs the following actions: 1. It reads characters from the input sequence, starting at theappend position, and appends them to the given string buffer. Itstops after reading the last character preceding the previous match,that is, the character at index start() - 1. 2. It appends the given replacement string to the string buffer. 3. It sets the append position of this matcher to the index ofthe last character matched, plus one, that is, to end(). The replacement string may contain references to subsequencescaptured during the previous match: Each occurrence of ${name} or $gwill be replaced by the result of evaluating the corresponding group(name) or group(g)respectively. For $g,the first number after the $ is always treated as part ofthe group reference. Subsequent numbers are incorporated into g ifthey would form a legal group reference. Only the numerals ‘0‘through ‘9‘ are considered as potential components of the groupreference. If the second group matched the string "foo", forexample, then passing the replacement string "$2bar" wouldcause "foobar" to be appended to the string buffer. A dollarsign ($) may be included as a literal in the replacementstring by preceding it with a backslash ($). Note that backslashes () and dollar signs ($) inthe replacement string may cause the results to be different than if itwere being treated as a literal replacement string. Dollar signs may betreated as references to captured subsequences as described above, andbackslashes are used to escape literal characters in the replacementstring. This method is intended to be used in a loop together with the appendTail and find methods. Thefollowing code, for example, writes one dog two dogs in theyard to the standard-output stream: Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toString());
以上是关于String替换占位符的主要内容,如果未能解决你的问题,请参考以下文章
[Java]_[初级]_[使用正则高效替换字符串的多个占位符为多个值]
[Java]_[初级]_[使用正则高效替换字符串的多个占位符为多个值]