import java.io.*;
import java.util.*;
import java.util.regex.*;public class IOtest
{
    public static void main(String[] args) throws IOException
    {
        String aLine = new String();
        String matchedString = new String();
        String allString = new String();
        
        String regex = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*";   // Regex definition
                
        try{            BufferedReader in = new BufferedReader( new FileReader("test.txt"));   //connect to a text file
            Pattern p = Pattern.compile(regex);  
            
            while((aLine = in.readLine())!=null){                                  // read line by line
                Matcher m = p.matcher(aLine);
                while(m.find()){
                    int start = m.start(0);
                    int end = m.end(0);
                    matchedString = aLine.substring(start, end);
                    allString = matchedString + "\n" +  allString  ;        
                }
            }
 
            System.out.println(allString);
             
            BufferedWriter out = new BufferedWriter( new FileWriter("newTest.txt"));
            out.write(allString);            in.close();
            out.close();
        }
        
        catch(IOException e){
            System.out.println("Oops!");
        }
    
    }
}
这代码的初衷是要 匹配 文件中的所有 电子邮件地址, 然后 按照每行一个的方式输出, 还有存入另一文件.这里我有两个问题1. System.out.println出来的邮件地址的确是一行一个,但是为什么新file中的邮件地址是连在一起的呢?2. 小弟第一次学正规表达式, 有个想法, 是否可以定义自己的一个regex , 比如上面那段邮件地址的regex 
   String emailRegex = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*";   
   可否把它包装起来,用在其他的regex中,直接引用emailRegex的名字,也就是说当成\w 这样的东西使用.谢谢大家