正则表达式

1.正则表达式的几个特殊的方法:

(1) boolean matches(String regex):判断该字符串是否匹配指定的正则表达式(regex)

(2) String replaceAll(String regex,String replacement):用replacement替换字符串中所有匹配指定正则表达式regex的字符

(3) String replaceFirst(String regex,String replacement):用replacement替换字符串中第一个匹配指定正则表达式regex的字符

(4) String[] split(String regex):根据指定正则表达式拆分该字符串后得到的字符串数组

2.正则表达式支持的数量标识符有如下几种模式:

(1)Greedy(贪婪模式):贪婪模式是一直匹配下去,直到无法匹配

(2)Reluctant(勉强模式):用问号(?)表示,它只匹配最少的字符

import java.util.Calendar;
public class TestRegular 
{
	public static void main(String[] args) 
	{
		String str="hello  world";
		//贪婪模式
		System.out.println(str.replaceFirst("\\w*","."));
		//勉强模式
		System.out.println(str.replaceFirst("\\w*?","."));
		//占用模式
		System.out.println(str.replaceFirst("\\w*+","."));
	}
}

3.Pattern对象是正则表达式编译后在内存中的表示形式,因此,正则表达式必须先被译成Pattern对象,然后再利用Pattern对象创建对应的Matcher对象。而执行匹配所涉及的状态保留在Matcher对象中

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindGroup 
{
	public static void main(String[] args) 
	{
		//Pattern提供一个正则表达式,而matcher提供字符串
		Matcher m=Pattern.compile("\\w+").matcher("java is very easy!");
		//从字符串中找到与正则表达式匹配的字符串
		while(m.find()){
			//输出上一次找到的字符串
			System.out.println(m.group());		
		}
		int i=0;
		//从i处开始扫描字符串,查找匹配字符串
		while(m.find(i)){
			System.out.println(m.group()+"\t");
			i++;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值