正则工具-ReUtil

    其中牵涉到多个对象,想用的时候真心记不住。好吧,既然功能如此常用,我就封装一下:

    1. * 获得匹配的字符串
    2. *
    3. * @param pattern 编译后的正则模式
    4. * @param content 被匹配的内容
    5. * @param groupIndex 匹配正则的分组序号
    6. */
    7. public static String get(Pattern pattern, String content, int groupIndex) {
    8. Matcher matcher = pattern.matcher(content);
    9. if (matcher.find()) {
    10. return matcher.group(groupIndex);
    11. }
    12. }
    13. /**
    14. * 获得匹配的字符串
    15. *
    16. * @param regex 匹配的正则
    17. * @param content 被匹配的内容
    18. * @param groupIndex 匹配正则的分组序号
    19. */
    20. public static String get(String regex, String content, int groupIndex) {
    21. Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
    22. }

    使用

    抽取多个分组然后把它们拼接起来

    1. String resultExtractMulti = ReUtil.extractMulti("(\\w)aa(\\w)", content, "$1-$2");
    2. Assert.assertEquals("Z-a", resultExtractMulti);

    ReUtil.delFirst

    查找所有匹配文本

    1. List<String> resultFindAll = ReUtil.findAll("\\w{2}", content, 0, new ArrayList<String>());
    2. ArrayList<String> expected = CollectionUtil.newArrayList("ZZ", "Za", "aa", "bb", "bc", "cc", "12", "34");
    3. Assert.assertEquals(expected, resultFindAll);

    ReUtil.getFirstNumber

    找到匹配的第一个数字

    1. Integer resultGetFirstNumber = ReUtil.getFirstNumber(content);
    2. Assert.assertEquals(Integer.valueOf(1234), resultGetFirstNumber);

    ReUtil.replaceAll

    通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串

    1. //此处把1234替换为 ->1234<-
    2. String replaceAll = ReUtil.replaceAll(content, "(\\d+)", "->$1<-");
    3. Assert.assertEquals("ZZZaaabbbccc中文->1234<-", replaceAll);

    转义给定字符串,为正则相关的特殊符号转义