Java利用正则提取一行中多个目标 - 高飞网
128 人阅读

Java利用正则提取一行中多个目标

2016-12-09 18:09:25

现在有如下的字符串:

<abc@163.com23><abc.all@163.com><abc_des@163.com><abc123@163.com

我们想提取其中的邮箱。

使用正则:

;([a-z0-9_\\.]+@163.com)

正则的含义为:

以;开始,以@163.com结束,邮箱名规则为a-z的字母、0-9数字、下划线或.。由于.在正则中表示特殊含义("\n" 之外的任何单个字符),因此使用了转义

完整代码:


public class ExtractMail {
    static String s = "<abc@163.com23><abc.all@163.com><abc_des@163.com><abc123@163.com";

    public static void main(String[] args) {// /
        Pattern p = Pattern.compile(";([a-z0-9_\\.]+@163.com)");
        Matcher matcher = p.matcher(s);
        while (matcher.find()) {
            String mail = matcher.group(1);
            System.out.println(mail);
        }
    }

}

输出:

abc@163.com
abc.all@163.com
abc_des@163.com
abc123@163.com     

    这里关键点在于find()方法,来看下find方法的说明:

/**
     * Attempts to find the next subsequence of the input sequence that matches
     * the pattern.
     *
     * <p> This method starts at the beginning of this matcher's region, or, if
     * a previous invocation of the method was successful and the matcher has
     * not since been reset, at the first character not matched by the previous
     * match.
     *
     * <p> If the match succeeds then more information can be obtained via the
     * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods.  </p>
     *
     * @return  <tt>true</tt> if, and only if, a subsequence of the input
     *          sequence matches this matcher's pattern
     */
    public boolean find() {}

    即:尝试查找与该模式匹配的输入序列的下一个子序列。 

还没有评论!
54.224.143.233