加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用正则表达式提取字符串中的内容

发布时间:2020-12-14 01:54:06 所属栏目:百科 来源:网络整理
导读: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
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("绿");
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读