java的正则循环匹配(手写字符串分割方法)

废话不多说,直接撸代码:

/**
 * @Describe: 手写字符串分割
 **/
public class Test {
    public static void main(String[] args) {
        String str = "ab,#cd,#e";
        String split = ",#";
        System.out.println(split(str, split));

        String regex = "[^(,#)]+";
        System.out.println(splitByRegex(str, regex));
    }


    /*
     * @describe: 实现按指定字符进行字符串分割
     * @param str
     * @param split
     * @return: java.util.List<java.lang.String>
    */
    public static List<String> split(String str, String split) {
        List<String> result = new ArrayList<>();
        int start = 0;
        while(start < str.length() - 1) {
            int in = str.indexOf(split, start);
            if (in == -1) {
                result.add(str.substring(start));
                break;
            }
            if (in > 0) {
                result.add(str.substring(start, in));
            }
            start = in + split.length();
        }

        return result;

    }

    /*
     * @describe: 实现按正则表达式实现字符串分割
     * @param str
     * @param regex
     * @return: java.util.List<java.lang.String>
    */
    public static List<String> splitByRegex(String str, String regex) {
        List<String> result = new ArrayList<>();

        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(str);

        while (matcher.find()) { // 往后逐个匹配
            result.add(matcher.group());
        }
        
        return result;

    }
}

输出结果:

[ab, cd, e]
[ab, cd, e]


说明:

正则表达式进行字符串分割,该方法入参【regex】也可以传入正常的分割字符串,如:“,#”,然后组装成正则表达式:"[^("+regex+")]+"即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值