java 正则表达式的用法

    科技2022-07-11  86

    // 按指定模式在字符串查找 String line = "This order was placed for QT3000! OK?"; String pattern = "(\\D*)(\\d+)(.*)"; // 创建 Pattern 对象 Pattern r = Pattern.compile(pattern); // 现在创建 matcher 对象 Matcher m = r.matcher(line);

    找到所有匹配到的子串

    String exp = "(.*?)\\((.*?)\\),"; Pattern pattern = Pattern.compile(exp); String a = "Mary(12),Tom(20),Jhon(32),"; Matcher matcher = pattern.matcher(a); while (matcher.find()) { // 打印子串中的所有内容:0是完整子串。n要取等 int n = matcher.groupCount(); System.out.print(n); for (int i = 0; i <= n; i++) { System.out.print(" " + matcher.group(i)); } System.out.println(); }

    group()方法如果里面填写的是数字,那么返回的就是括号里面的内容 如果里面是名字,那么返回的就是尖括号里面的内容 所以,以数字取本质上和用名字取是一样的 java 获取正则表达式自身里面的变量

    private static String[] getAllExpName(String exp) { String reg = "<(\\w+)>"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(exp); String[] ans = new String[]; int cnt = 0; while (matcher.find()){ ans[cnt++] = matcher.group(); } return ans; }
    Processed: 0.019, SQL: 8