施用正则表达式提取字符串中的内容
使用正则表达式提取字符串中的内容
package cn.com.songjy.test; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest { public static void main(String[] args) { String regex = "\\[{1}(.+)\\]{1}"; String str = "短信中包含以下敏感字:[fuck,shit,bitch]并且号码中包含以下黑名单:张三-13701234567,李四-18701234567"; System.out.print("敏感字如下:"); System.out.println(getKeyWords(regex, str)); System.out.print("黑名单号码如下:"); System.out.println(getMobiles(str)); System.out.println("字符替换:"+replaceStr("我喜欢红色")); } //提取 中括号中关键字 public static String getKeyWords(String regex,String str){ Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); if(m.find()){ return m.group(1); } return null; } //提取字符串中的手机号码 public static String getMobiles(String str) { Pattern p = Pattern.compile("(\\+86|)?(\\d{11})"); Matcher m = p.matcher(str); StringBuilder sb = new StringBuilder(); while (m.find()) { if(sb.length()>0) sb.append(","); sb.append(m.group(2)); } /* * 不加"()"也能将手机号码输出 添加"()"是为了筛选数据添加上去的, * 第一对"()"是为了获取字符串"+86",代码是System.out.println(m.group(1));, * 第二对"()"是获取11位纯数字电话号码, 本次的输出的手机号码中包含了"+86",如果只要11位数字号码, * 可将代码改为System.out.println(m.group(2)); */ //System.out.println(m.groupCount());// 该行代码是输出有几对"()",即捕获组个数,本次输出结果是2,因为有两对"()" return sb.toString(); } //替换字符 public static String replaceStr(String str){ String regex = "红"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); return m.replaceAll("绿"); } }