String str="life is a ( _movie)";
//获得一个正则表达式对象
Pattern p = Pattern.compile("life is a ( _movie)");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
为什么不能匹配
在正则中,有些符号需要用转义符号来定义,比如分组符号(),如果要匹配圆括号,需要转义,写成\(\)
需要注意的符号一共也没多少,字符集符号[],长度符号{}+*?,分组符号(),位置符号^$,预定义字母数字下划线符号.,字符集范围符号-,以及转义符号本身\
改成这样试试,记得添加转义符,直接在正则表达式中写()表示的是一个分组,不消费字符串,所以匹配不到原来字符串里的(),就导致整个匹配失败
String str="life is a ( _movie)";
//获得一个正则表达式对象
Pattern p = Pattern.compile("life is a \\( _movie\\)");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}