Home > Java > javaTutorial > body text

Java code example using regular expression to replace mobile phone number

黄舟
Release: 2017-09-19 09:54:20
Original
1643 people have browsed it

本文的主要内容是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);
  }
}
Copy after login

输出结果如下:


138****4571
Copy after login

这只是正则表达式的一个简单用法,下面我们拓展一下其他相关用法及具体介绍。

1,简单匹配

在java中字符串可以直接使用


String.matches(regex)
Copy after login

注意:正则表达式匹配的是所有的字符串

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");
}
Copy after login

此时还可以查找出匹配的多个分组,需要在正则表达式中添加上括号,一个括号对应一个分组


String str="xingming:lsz,xingbie:nv";
String cmd="xingming:([a-zA-Z]*),xingbie:([a-zA-Z]*)"&#39;
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");
}
Copy after login

3,查找并替换,占位符的使用


String str= “abcaabadwewewe”;
String str2 = str.replaceAll("([a])([a]|[d])","*$2")
str2为:abc*ab*dwewewe
Copy after login

将a或d前面的a替换成*,$为正则表达式中的占位符。

总结:

The above is the detailed content of Java code example using regular expression to replace mobile phone number. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template