Java -- 正则表达式

1. 正则表达式

2. 使用正则表达式

可以直接使用String提供的方法 也 可以使用Pattern 和 Matcher类,Pattern对象是正则表达式编译后在内存中的表示形式,因此正则表达式必须先编译为Pattern对象(可以多次利用),然后利用该对象创建对应的Matcher对象,执行匹配所涉及的状态保留在Matcher对象中,多个Matcher对象可共用一个Pattern.

例一:

public class Main {		
	public static void main(String[] args) throws IOException {
		
	String ip = "192-0-0-1";
	System.out.println( ip.matches("\d*-\d*-\d*-\d*") ); //直接用String
	System.out.println(ip.replaceFirst("\d*", "168"));
	System.out.println(ip.replaceFirst("\d?", "168"));
	String [] str = ip.split("-");
	for( String temp : str )	
		System.out.print(temp + "  ");
	System.out.println();
	
	Pattern p = Pattern.compile("\d*");
	Matcher m = p.matcher("192");
	System.out.println( m.matches() );
	
	System.out.println( Pattern.matches("\d*-\d*-\d*-\d*", "192-168-1-1") ); //直接使用Pattern静态方法,不可复用
	}	
}

例二:

public class Main {		
	public static void main(String[] args) throws IOException {
		
	Matcher m = Pattern.compile("\w+").matcher("hello java");
	while(m.find())
	{
		System.out.println(m.group() + " from " + m.start() + " to " + m.end());
	}
	
	int i=0;
	while(m.find(i))
	{
		System.out.print(m.group() + "	");
		i++;
	}	
	}	
}

输出结果:

hello from 0 to 5
java from 6 to 10
hello   ello    llo     lo      o       java    java    ava     va      a

例三:

public class Main {		
	public static void main(String[] args) throws IOException {
		
		String [] mails =
			{
				"12@163.com",
				"xiangjie55@qq.com",
				"xj626852095@qq.com",
				"xiangjie55@163.com",
				"12@163.com"
			};
		String mailRegEx = "\w{5,20}@\w+\.(com|org|cn|net)";
		Pattern mailPattern = Pattern.compile(mailRegEx);
		Matcher matcher = null;
		for( String mail : mails )
		{
			if( matcher==null )
			{
				matcher = mailPattern.matcher(mail);
			}
			else
			{
				matcher.reset(mail);
			}
			
			if( matcher.matches() )
			{
				System.out.println(mail + " format is OK");				
			}
			else
			{
				System.out.println(mail + " format is not OK");	
			}			
		}
	}	
}

输出结果:

12@163.com format is not OK
xiangjie55@qq.com format is OK
xj626852095@qq.com format is OK
xiangjie55@163.com format is OK
12@163.com format is not OK


 

原文地址:https://www.cnblogs.com/xj626852095/p/3648076.html