ORO demo

这里主要说明一下关于正则表达式的分组操作,如果要对一个pattern进行分组可以使用分组操作符号"()"来完成,比如:\d\w,因为没有显式的进行分组则\d\w是一组对应的group的index为0,但是如果我们处理其为(\d)(\w)则就执行了一次分组为0,1,2其中group(0)的效果等同于\d\w,group(1)匹配\d,group(2)匹配\w的内容。下面使用一个例子来说明分组的情况:
[code] public static void checkMatchGroup(String patternStr, String inputStr) {
try {
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
PatternMatcher matcher = new Perl5Matcher();
boolean isExist = matcher.contains(inputStr, pattern);
if (isExist) {
MatchResult res = matcher.getMatch();
int length = res.length();
for (int i = 0; i < length; i++) {
String g = res.group(i);
if(g!=null)
System.out.println(i + "=:" + g);
}
}
} catch (MalformedPatternException e) {
System.out.println("Error occur when checkMatchGroup:"
+ e.getMessage());
}
System.out.println("---------------------");
}[/code]

测试的代码如下:
[code] /*
* for this if we us the charset "?:" the group of (?:\\w+) will be ignored
* so the pattern (\\w)(\\d)(?:\\w+) has 3 groups,but we have on right to access
* the third part(\\w+),
* the result of "j2se333" as fallows:
* 0=:j2se333
* 1=:j
* 2=:2
* if we didn't add ?: as the prefix to \\w+ the result will be :
* 0=:j2se333
* 1=:j
* 2=:2
* 3=:se333
*/
checkMatchGroup("(\\w)(\\d)(?:\\w+)","j2se333");

/* Reluctant Qualifiers
* for using ? the result of "\d+?" for string "1234" will be get 1
* if we remove the '?' the result will be 1234
*/
checkMatchGroup("\\d+?","1234");
/*
*
*/
checkMatchGroup("(?=^255).*","255.0.0.1");
checkMatchGroup("(?=^255).*","223.0.0.1");[/code]

需要注意的一点是?:符号主要是告诉oro,对于匹配的内容不记忆其状态,也就是说无论是存在与否只要使用了?:我们无法通过group(i)来得到相应的内容
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值