首页 > 代码库 > groovy regex groups(groovy正则表达式组)
groovy regex groups(groovy正则表达式组)
先看一个java正则表达式的例子.
import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestMatch { public static void main(String[] args) { Pattern pattern = Pattern.compile("G.*"); Matcher matcher = pattern.matcher("Groovy"); System.out.println(matcher.matches()); }}
其实这个代码的意思就是Groovy是不是匹配正则表达式G.*
为了一个简单的判断是不是匹配,就写这么多代码。看groovy是如何实现的。
matcher = "Groovy" =~ /G.*/
println(matcher.matches())
2行代码搞定。
正则表达式组(regex groups)又怎么用?再看一个groovy的例子.
text = """
Lorem 1:30 PM ipsum dolor 12:00 PM sit amet, consectetuer adipiscing elit.
"""
HOUR = /10|11|12|[0-9]/
MINUTE = /[0-5][0-9]/
AM_PM = /AM|PM/
time = /($HOUR):($MINUTE) ($AM_PM)/
matcher = text =~ time
println(matcher[0] == ["1:30 PM", "1", "30", "PM"]) //First Match
println(matcher[0][0] == "1:30 PM") //First match group in the first match
println(matcher[0][1] == "1") //Second match group in the first match (HOUR)
println(matcher[0][2] == "30") //Third match group in the first match (MINUTE)
println(matcher[0][3] == "PM") //Fourth match group in the first match (AM_PM)
println(matcher[1] == ["12:00 PM", "12", "00", "PM"]) //Second Match
println(matcher[1][0] == "12:00 PM") //First match group in the second match
println(matcher[1][1] == "12") //Second match group in the second match (HOUR)
println(matcher[1][2] == "00") //Third match group in the second match (MINUTE)
println(matcher[1][3] == "PM") //Fourth match group in the second match (AM_PM)
其中time就可以认为是一个正则表达式组,它有三个“组员”: ($HOUR),($MINUTE),($AM_PM)
注意,用()括起来才表示是一个“组员”,否则每个字符都是一个组员.要注意一个问题matcher.matches()意思是“是否整个字符串都匹配正则表达式”,对于这个例子,虽然text中有2个匹配,但是matcher.matches()的结果是false,因为对于整个字符串来说不匹配.通过这个细节可以体会正则表达式组的作用.
再看一个例子:
matcher = ".groovyd,aa3" =~ /(\.groovy.),(aa.)/
println(matcher.matches())
println(matcher.getCount())
/(\.groovy.),(aa.)/有2个“组员”
再看一个例子:
matcher = ".groovyd,aa3" =~ /\.groovy.,aa./
println(matcher.matches())
/\.groovy.,aa./有12个组员.
参考资料:
1. http://groovy.codehaus.org/Tutorial+5+-+Capturing+regex+groups
2. http://groovy.codehaus.org/FAQ+-+RegExp
3. http://developer.51cto.com/art/200906/129179.htm
4. http://docs.oracle.com/javase/7/docs/api/
groovy regex groups(groovy正则表达式组)