您的位置:首页 > 编程语言 > Java开发

Java正则表达式Pattern类的用法

2014-10-23 23:24 295 查看
在java中写正则表达式需要用到Pattern 类的compile方法,使用此方法时要注意,不要在compile 里正则表达式,要把正则表达式放在外面定义好,再放在里面,否则会出一些诡异的问题

正确的写法:

String pat = ".*_(.*)_(.*?)\\.?\\[(.*)\\]\\[.*\\]\\.txt";
Pattern p_pc = Pattern.compile(pat);
Matcher m_other = p_pc.matcher(CNfileName);

if (m_other.find()) {
System.out.println(m_other.group(1));
System.out.println(m_other.group(2));
System.out.println(m_other.group(3));
}


错误的写法如下:

Pattern p_pc = Pattern.compile(".*_(.*)_(.*?)\\.?\\[(.*)\\]\\[.*\\]\\.txt");
Matcher m_other = p_pc.matcher(CNfileName);

if (m_other.find()) {
System.out.println(m_other.group(1));
System.out.println(m_other.group(2));
System.out.println(m_other.group(3));
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: