您的位置:首页 > 编程语言 > Java开发

Java 4000 正则表达式

2016-06-23 19:26 375 查看
package com.mipo.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Pattern类 :Java过滤特殊字符的正则表达式
* 正则表达式的编译表示形式。
* 指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。
* 执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。
* 因此,典型的调用顺序是
* Pattern p = Pattern.compile("a*b");
* Matcher m = p.matcher("aaaaab");
* boolean b = m.matches();
* 在仅使用一次正则表达式时,可以方便地通过此类定义 matches 方法。此方法编译表达式并在单个调用中将输入序列与其匹配。语句
* boolean b = Pattern.matches("a*b", "aaaaab");
* 等效于上面的三个语句,尽管对于重复的匹配而言它效率不高,因为它不允许重用已编译的模式。
* 此类的实例是不可变的,可供多个并发线程安全使用。Matcher 类的实例用于此目的则不安全。
* @author Administrator
*
*/
public class TestPattern {
/*
compile
public static Pattern compile(String regex)将给定的正则表达式编译到模式中。

参数:
regex - 要编译的表达式
抛出:
PatternSyntaxException - 如果表达式的语法无效

*/

/*
matcher
public Matcher matcher(CharSequence input)创建匹配给定输入与此模式的匹配器。

参数:
input - 要匹配的字符序列
返回:
此模式的新匹配器
*/

/*
matches
public boolean matches()尝试将整个区域与模式匹配。
如果匹配成功,则可以通过 start、end 和 group 方法获取更多信息。

返回:
当且仅当整个区域序列匹配此匹配器的模式时才返回 true。
*/

/*
matches
public static boolean matches(String regex,
CharSequence input)编译给定正则表达式并尝试将给定输入与其匹配。
调用此便捷方法的形式

Pattern.matches(regex, input);与表达式
Pattern.compile(regex).matcher(input).matches() 的行为完全相同。
如果要多次使用一种模式,编译一次后重用此模式比每次都调用此方法效率更高。

参数:
regex - 要编译的表达式
input - 要匹配的字符序列
抛出:
PatternSyntaxException - 如果表达式的语法无效
*/

public static void main(String[] args) {
// TODO Auto-generated method stub
//用正则表达式验证以abc开头
String rex = "^abc";//正则表达式:以abc开头
String str = "abc";//源字符串

//方法一:对于多次使用同一模式,此法效率更高
Pattern p = Pattern.compile(rex);//将正则表达式编译到模式p中
Matcher ma = p.matcher(str);//创建匹配器ma(匹配给定输入的字符串str和模式p)
boolean b1 = ma.matches();//尝试将整个区域与模式匹配,若匹配成功,返回true
System.out.println(b1);

//方法二:如果要多次使用一种模式,编译一次后重用此模式比每次都调用此方法效率更高。
boolean b2 = Pattern.matches("^abc", "abab");//编译给定正则表达式并尝试将给定输入与其匹配。
System.out.println(b2);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息