问题: 匹配"联想 昭阳e280l"之中的"邵阳" (其中联想 邵阳之间含有(0-n个)空格)。
解决方案:
public class Question {
public static void main(String[] args) {
String regex="联想 昭阳e280l";
Pattern p=Pattern.compile("(?<=联想)\\s*([\u4e00-\u9fa5]*)\\w*");
Matcher m=p.matcher(regex);
System.out.println(m.find());
System.out.println(m.group(1));
}
}
说明:
(?<=exp)也叫零宽度正回顾后发断言,它断言自身出现的位置的前面能匹配表达
式exp。比如(?<=\bre)\w+\b会匹配以re开头的单词的后半部分(除了re以外的部分),
例如在查找reading a book时,它匹配ading
另外一种类似的匹配方式,本质上与上面一样。贴出代码只是想说说明分组的相关问题。
public static void main(String[] args) {
String regex="联想昭阳e280l";
// (联想)为第一组 ([\\u4e00-\\u9fa5]*)为第二组
Pattern p=Pattern.compile("(?<=(联想))\\s*([\\u4e00-\\u9fa5]*)(?=\\w+)");
Matcher m=p.matcher(regex);
while(m.find()){
int groupCount=m.groupCount();
System.out.println("groupCount:"+groupCount+"-->"+ m.group());
for(int i=1;i<=groupCount;i++){
System.out.println(m.group(i));
}
}
}