正则表达式学习-位置匹配(二)

2014-11-24 09:14:44 · 作者: · 浏览: 5

contentPanel.add(newJLabel("Downloading messages..."));

setContentPane(contentPanel);

【 //Size dialog boxto components.】

pack();

【 //Center dialogbox over application.】

setLocationRelativeTo(parent);

}

分析:^\s*//.*$将匹配一个字符串的开始,然后是任意多个空白字符,再后面是//,再往后是任意文本,最后是一个字符串的结束。不过这个模式只能找出第一条注释,加上( m)前缀后,将把换行符视为一个字符串分隔符,这样就可以把每一行注释匹配出来了。

java代码实现如下(文本保存在text.txt文件中):


[java]
public static String getTextFromFile(String path) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
StringBuilder sb = new StringBuilder();
char[] cbuf = new char[1024];
int len = 0;
while(br.ready() && (len = br.read(cbuf)) > 0){
br.read(cbuf);
sb.append(cbuf, 0, len);
}
br.close();
return sb.toString();
}
public static void multilineMatch() throws Exception{
String text = getTextFromFile("E:/text.txt");
String regex = "( m)^\\s*//.*$";
Matcher m = Pattern.compile(regex).matcher(text);
while(m.find()){
System.out.println(m.group());
}
}
输出结果如下:
//Call super constructor, specifying that dialog box is modal.
//Set dialog box title.
//Instruct window not to close when the "X" is clicked.
//Put a message with a nice border in this dialog box.

//Size dialog box to components.
//Center dialog box over application.


五、小结

正则表达式不仅可以用来匹配任意长度的文本块,还可以用来匹配出现在字符串中特定位置的文本。\b用来指定一个单词边界(\B刚好相反)。^和$用来指定单词边界。如果与( m)配合使用,^和$还将匹配在一个换行符处开头或结尾的字符串。在下一篇中将介绍子表达式的使用。