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

正则表达式

发布时间:2020-12-13 22:41:45 所属栏目:百科 来源:网络整理
导读:1.正则表达式的几个特殊的方法: (1) boolean matches(String regex):判断该字符串是否匹配指定的正则表达式(regex) (2) String replaceAll(String regex,String replacement):用replacement替换字符串中所有匹配指定正则表达式regex的字符 (3) String repla

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++;
		}
	}
}

(编辑:李大同)

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

    推荐文章
      热点阅读