JAVA 正则表达式陈广佳版本(超详细)

2020-03-05 18:01:51王振洲

为了简便起见,我们不再和从数据库里读出,而是构造一个包含同样内容的字符串变量,程序片段如下:

try{
String content="['kevin] [名词](人名凯文){(Kevin loves comic./凯文爱漫画/名词:凯文) (Kevin is living in ZhuHai now./凯文现住在珠海/名词: 凯文)}";
String ps1="//{.+//}";
String ps2="//([^)]+//)";
String ps3="([^(]+)/(.+)/(.+):([^)]+)";
String sentence;
PatternCompiler orocom=new Perl5Compiler();
Pattern pattern1=orocom.compile(ps1);
Pattern pattern2=orocom.compile(ps2);
Pattern pattern3=orocom.compile(ps3);
PatternMatcher matcher=new Perl5Matcher();
//先找出整个例句部分
if (matcher.contains(content,pattern1)) {
MatchResult result=matcher.getMatch();
String example=result.toString();
PatternMatcherInput input=new PatternMatcherInput(example);
//分别找出例句一和例句二
while (matcher.contains(input,pattern2)){
result=matcher.getMatch();
sentence=result.toString();
//把每个例句里的各项用分组的办法分隔出来
if (matcher.contains(sentence,pattern3)){
result=matcher.getMatch();
System.out.println("英文句: "+result.group(1));
System.out.println("句子中文翻译: "+result.group(2));
System.out.println("词性: "+result.group(3));
System.out.println("意思: "+result.group(4));
}
}
}
}
catch(Exception e) {
System.out.println(e);
}

输出结果为:
英文句: Kevin loves comic.
句子中文翻译: 凯文爱漫画
词性: 名词
意思: 凯文
英文句: Kevin is living in ZhuHai now.
句子中文翻译: 凯文现住在珠海
词性: 名词
意思: 凯文

★查找替换:
以上的两个应用都是单纯在查找字符串匹配方面的,我们再来看一下查找后如何对目标字符串进行替换。

例如我现在想把第二个例句进行改动,换为:Kevin has seen《LEON》seveal times,because it is a good film./ 凯文已经看过《这个杀手不太冷》几次了,因为它是一部好电影。/名词:凯文。

也就是把
['kevin] [名词](人名凯文){(Kevin loves comic./凯文爱漫画/名词: 凯文)( Kevin is living in ZhuHai now. /凯文现住在珠海/名词: 凯文)}

改为:
['kevin] [名词](人名凯文){(Kevin loves comic./凯文爱漫画/名词: 凯文)( Kevin has seen《LEON》seveal times,because it is a good film./ 凯文已经看过《这个杀手不太冷》几次了,因为它是一部好电影。/名词:凯文。)}

之前,我们已经了解Util.substitute()方法与Substiution接口,以及Substiution的两个实现类StringSubstitution和Perl5Substitution,我们就来看看怎么用Util.substitute()方法配合Perl5Substitution来完成我们上面提出的替换要求,确定正则表达式:

我们要先找到其中的整个例句部分,也就是由大括号包起来的字串,并且把两个例句分别分组,所以正则表达式为:"/{(/([^)]+/))(/([^)]+/))/}",如果用替换变量来代替分组,那么上面的表达式可以看为"/{$1$2/}",这样就可以更容易看出替换变量与分组间的关系。