1 找出字符串中的电话号码
代码示例
import java.util.regex.*; public class FindGroup { public static void main(String[] args) { // 使用字符串模拟从网络上得到的网页源码 String str = "我想求购一本《Java典型应用》,尽快联系我13500006666" + "交朋友,电话号码是13611125565" + "出售二手电脑,联系方式15899903312"; // 创建一个Pattern对象,并用它建立一个Matcher对象 // 该正则表达式只抓取13X和15X段的手机号, // 实际要抓取哪些电话号码,只要修改正则表达式即可。 Matcher m = Pattern.compile("((13\\d)|(15\\d))\\d{8}") .matcher(str); // 将所有符合正则表达式的子串(电话号码)全部输出 while(m.find()) { System.out.println(m.group()); } } }
运行结果
13500006666
13611125565
15899903312
2 返回目标字符串中的各个子串,以及各子串在目标字符串中的位置
代码示例
import java.util.regex.*; public class StartEnd { public static void main(String[] args) { // 创建一个Pattern对象,并用它建立一个Matcher对象 String regStr = "Java is very easy!"; System.out.println("目标字符串是:" + regStr); Matcher m = Pattern.compile("\\w+") .matcher(regStr); while(m.find()) { System.out.println(m.group() + "子串的起始位置:" + m.start() + ",其结束位置:" + m.end()); } } }
运行结果
目标字符串是:Java is very easy!
Java子串的起始位置:0,其结束位置:4
is子串的起始位置:5,其结束位置:7
very子串的起始位置:8,其结束位置:12
easy子串的起始位置:13,其结束位置:17
3 检验一个邮箱是否是一个合法的邮箱
代码示例
import java.util.regex.*; public class MatchesTest { public static void main(String[] args) { String[] mails = { "798103175@qq.com","cakin24@163.com","chengqiuming@w3.org","c00303563@abc.xx" }; String mailRegEx = "\\w{3,20}@\\w+\\.(com|org|cn|net|gov)"; Pattern mailPattern = Pattern.compile(mailRegEx); Matcher matcher = null; for (String mail : mails) { if (matcher == null) { matcher = mailPattern.matcher(mail); } else { matcher.reset(mail); } String result = mail + (matcher.matches() ? "是" : "不是") + "一个有效的邮件地址!"; System.out.println(result); } } }
运行结果
798103175@qq.com是一个有效的邮件地址!
cakin24@163.com是一个有效的邮件地址!
chengqiuming@w3.org是一个有效的邮件地址!
c00303563@abc.xx不是一个有效的邮件地址!
4 将一个字符串中以“re”开头的单词替换为其它字符串
代码示例
import java.util.regex.*; public class ReplaceTest { public static void main(String[] args) { String[] msgs = { "Java has regular expressions in JDK1.4","regular expressions now expressing in Java","Java represses oracular expressions" }; Pattern p = Pattern.compile(" re\\w*|^re\\w*"); Matcher matcher = null; for (int i = 0 ; i < msgs.length ; i++) { if (matcher == null) { matcher = p.matcher(msgs[i]); } else { matcher.reset(msgs[i]); } System.out.println(matcher.replaceAll(" 笑笑:)")); } } }
运行结果
Java has 笑笑:) expressions in JDK1.4
笑笑:) expressions now expressing in Java
Java 笑笑:) oracular expressions
5 String类正则表达式的应用
代码示例
import java.util.*; public class StringReg { public static void main(String[] args) { String[] msgs = { "Java has regular expressions in JDK1.4","Java represses oracular expressions" }; for (String msg : msgs) { System.out.println(msg.replaceFirst("re\\w*","哈哈:)")); System.out.println(Arrays.toString(msg.split(" "))); } } }
运行结果
Java has 哈哈:) expressions in JDK1.4[Java,has,regular,expressions,in,JDK1.4]哈哈:) expressions now expressing in Java[regular,now,expressing,Java]Java 哈哈:) oracular expressions[Java,represses,oracular,expressions]