用于进行正则匹配

object Test extends App { var rules = ArrayBuffer(“^.*http://b2c.csair.com/ita/intl/app.*$”, “^.*/B2C40/query/jaxb/direct/query.ao.*$”, “^.2*/B2C40/modules/bookingnew/main/flightSelectDirect.html\\?.*$”) var request=”POST /B2C40/query/jaxb/direct/query.ao HTTP/1.1″ //对数组中的每个正则表达式,依次进行匹配 for(rule<-rules){ //matches的参数是正则表达式 if(request.matches(rule)){ println(“匹配成功”) }else{ println(“匹配失败”) } }}

运行结果

匹配失败匹配成功匹配失败 matches方法源码 public boolean matches(String regex) {//实际调用了Pattern的静态方法 return Pattern.matches(regex, this); }

继续深入

public static boolean matches(String regex, CharSequence input) {//对正在表达式进行编译 Pattern p = Pattern.compile(regex); //利用正则表达式进行匹配 Matcher m = p.matcher(input); //返回是否匹配,布尔类型 return m.matches(); } 案例 //单独用matches方法只能判断是否匹配,不能进行匹配后的提取 private val bool: Boolean = “apple Store has much apple”.matches(“^a.*”) println(bool)//true

如果要进行匹配后还要进一步操作,比如提取匹配内容,则需要采用下面这种写法

def test = { val pattern: Pattern = Pattern.compile(“^a.*e\\s”) val matcher: Matcher = pattern.matcher(“apple Store is very beautiful”) if (matcher.find) { //提取匹配内容 println(matcher.group()) //apple Store } } 总结 单独用matches方法只能用于判断是否匹配compile.matcher,find,group联合使用可以提取匹配到的内容