java 正则 分组

来源:互联网 发布:怿不甚知书 编辑:程序博客网 时间:2024/06/16 01:02
package filesearch;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Regex {    public static void main(String[] args) {        //String ss = "";        String msg ="Power Supply 1   | 58h | ok  | 10.1 | Presence detected "        +"Power Supply 2   | 58h | nok  | 10.1 | Presence detected";        //Pattern类用于创建一个正则表达式,构造器私有,不能直接建立对象        Pattern pattern = Pattern.compile("(\\S+\\s\\S+\\s\\d)\\s+\\|\\s\\S+\\s\\S+\\s(\\S+)");        //Matcher类提供了对正则表达式的分组支持        Matcher matcher = pattern.matcher(msg);        //int i=0;        while (matcher.find()) {            System.out.println(matcher.group(0));            System.out.println(matcher.group(1));            System.out.println(matcher.group(2));        }    }    /*输出:    Power Supply 1   | 58h | ok    Power Supply 1    ok    Power Supply 2   | 58h | nok    Power Supply 2    nok    */}