关闭

java正则表达式相关类的使用

标签: 正则表达式string
157人阅读 评论(0) 收藏 举报
分类:
</pre><pre name="code" class="java">import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestZhengZe {

	public static void main(String[] args) {
		//匹配数字
		Pattern mac = Pattern.compile("-?(0|([1-9][0-9]*))(\\.[0-9]+)?");
		System.out.println(mac.matcher("101.001").matches());
		System.out.println(mac.matcher("-00.000").matches());
		
		//截取字符串中的数字和将数字括起来
		Pattern pattern = Pattern.compile("[0-9]+");
		String s = "aa123cc001qwe";
		StringBuilder newStr = new StringBuilder(s);
		Matcher matcher = pattern.matcher(s);
		int i = 0;
		while(matcher.find()){
			int start = matcher.start();
			int end = matcher.end();
			System.out.println(s.substring(start, end));
			newStr.insert(start+i, '[');
			newStr.insert(end+1+i, ']');
			i = i + 2;
			System.out.println(newStr.toString());
		}
		
		//替换指定的字符串
		Pattern patt = Pattern.compile("[a-z]+");
		String ss = "1321ase45212zxB11NBV1";
		Matcher match = patt.matcher(ss);
		ss = match.replaceAll("*");
		System.out.println(ss);
		
		//split分割字符串
		Pattern pa = Pattern.compile("[A-Z]+");
		String[] strArrays = pa.split("123ZAS321ZZ222");
		for(String st:strArrays){
			System.out.println(st);
		}
	}

}
结果:
<img src="http://img.blog.csdn.net/20160601162029351?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1625次
    • 积分:154
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条