正则表达式教程之位置匹配详解(2)

         publicDownloadingDialog(Frame parent){
【              //Call superconstructor, specifying that dialog box is modal.】
                   super(parent,true);
【              //Set dialog boxtitle.】
                   setTitle("E-mailClient");
【              //Instruct windownot to close when the "X" is clicked.】
                   setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
【              //Put a messagewith a nice border in this dialog box.】
                   JPanelcontentPanel = new JPanel();
                   contentPanel.setBorder(BorderFactory.createEmptyBorder(5,5, 5, 5));
                   contentPanel.add(newJLabel("Downloading messages..."));
                   setContentPane(contentPanel);
【              //Size dialog boxto components.】
                   pack();
【              //Center dialogbox over application.】
                   setLocationRelativeTo(parent);
         }

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

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

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)配合使用,^和$还将匹配在一个换行符处开头或结尾的字符串。在接下来的文章中将介绍子表达式的使用。

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:

正则表达式在线生成工具:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjsfyf.html