是的,在Java中,正则表达式可以用来替换字符串中的数字。你可以使用Pattern
和Matcher
类来实现这个功能。以下是一个简单的示例:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReplaceDigits {
public static void main(String[] args) {
String input = "今天是2021年6月30日,晚上8点40分。";
String pattern = "\\d+"; // 匹配一个或多个数字
String replacement = "X"; // 替换为字符X
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(input);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result, replacement);
}
matcher.appendTail(result);
System.out.println(result.toString());
}
}
输出结果:
今天是XXXX年XX月XX日,晚上X点XX分。
在这个示例中,我们使用了正则表达式\\d+
来匹配一个或多个连续的数字,并将它们替换为字符X
。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。