📄 e430. searching and replacing with nonconstant values using a regular expression.txt
字号:
The simplest way to replace all occurrences of a pattern in a CharSequence is to use Matcher.replaceAll(). However, this method is restricted to replacement values that are constant. If the replacement value is dynamic (e.g., converting the match to uppercase), Matcher.appendReplacement() must be used.
This example demonstrates the use of Matcher.appendReplacement() by converting all words that match [a-zA-Z]+[0-9]+ to uppercase.
CharSequence inputStr = "ab12 cd efg34";
String patternStr = "([a-zA-Z]+[0-9]+)";
// Compile regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
// Replace all occurrences of pattern in input
StringBuffer buf = new StringBuffer();
boolean found = false;
while ((found = matcher.find())) {
// Get the match result
String replaceStr = matcher.group();
// Convert to uppercase
replaceStr = replaceStr.toUpperCase();
// Insert replacement
matcher.appendReplacement(buf, replaceStr);
}
matcher.appendTail(buf);
// Get result
String result = buf.toString();
// AB12 cd EFG34
Related Examples
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -