本文的主要内容是java语言中正则表达式替换手机号的第4到第7位,实现方法十分简单,同时涉及了一些正则表达式的相关用法,需要的朋友可以参考下。
在日常生活中,我们经常会遇到将一个手机号的4-7位字符串用正则表达式替换为为星号“*”。这是出于对安全性和保护客户隐私的考虑将程序设计成这样的。下面我们就来看看具体代码。
package test0914;
public class mobile {
public static void main(string[] args) {
string mobile = "13856984571";
mobile = mobile.replaceall("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
system.out.println(mobile);
}
}
输出结果如下:
138****4571
这只是正则表达式的一个简单用法,下面我们拓展一下其他相关用法及具体介绍。
1,简单匹配
在java中字符串可以直接使用
string.matches(regex)
注意:正则表达式匹配的是所有的字符串
2,匹配并查找
找到字符串中符合正则表达式的substring,结合pattern matcher 如下实例取出尖括号中的值
string str = "abcdefefg";
string cmd = "<[^\\s]*>";
pattern p = pattern.compile(cmd);
matcher m = p.matcher(str);
if(m.find()){
system.out.println(m.group());
}else{
system.out.println("not found");
}
此时还可以查找出匹配的多个分组,需要在正则表达式中添加上括号,一个括号对应一个分组
string str="xingming:lsz,xingbie:nv";
string cmd="xingming:([a-za-z]*),xingbie:([a-za-z]*)"'
pattern p = pattern.compile(cmd);
matcher m = p.matcher(str);
if(m.find()){
system.out.println("姓名:"+m.group(1));
system.out.println("性别:"+m.group(2));
}else{
system.out.println("not found");
}
3,查找并替换,占位符的使用
string str= “abcaabadwewewe”;
string str2 = str.replaceall("([a])([a]|[d])","*$2")
str2为:abc*ab*dwewewe
将a或d前面的a替换成*,$为正则表达式中的占位符。
总结:
以上就是java使用正则表达式替换手机号的代码实例的详细内容。