Java正则替换手机号代码实例
在日常生活中,我们经常会遇到将一个手机号的4-7位字符串用正则表达式替换为为星号“*”。这是出于对安全性和保护客户隐私的考虑将程序设计成这样的。下面我们就来看看具体代码。
packageTest0914; publicclassMobile{ publicstaticvoidmain(String[]args){ Stringmobile="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,结合PatternMatcher如下实例取出尖括号中的值
Stringstr="abcdefefg"; Stringcmd="<[^\\s]*>"; Patternp=Pattern.compile(cmd); Matcherm=p.matcher(str); if(m.find()){ System.out.println(m.group()); }else{ System.out.println("notfound"); }
此时还可以查找出匹配的多个分组,需要在正则表达式中添加上括号,一个括号对应一个分组
Stringstr="xingming:lsz,xingbie:nv"; Stringcmd="xingming:([a-zA-Z]*),xingbie:([a-zA-Z]*)"' Patternp=Pattern.compile(cmd); Matcherm=p.matcher(str); if(m.find()){ System.out.println("姓名:"+m.group(1)); System.out.println("性别:"+m.group(2)); }else{ System.out.println("notfound"); }
3,查找并替换,占位符的使用
Stringstr=“abcaabadwewewe”; Stringstr2=str.replaceAll("([a])([a]|[d])","*$2") str2为:abc*ab*dwewewe
将a或d前面的a替换成*,$为正则表达式中的占位符。
总结:
以上就是本文关于正则表达式替换手机号中间四位的具体代码和正则表达式的一些相关用法,希望对大家有所帮助。