Equivalent to StringTokenizer with multiple characters delimiters

前端 未结 3 1433
你的背包
你的背包 2021-01-18 07:34

I try to split a String into tokens.

The token delimiters are not single characters, some delimiters are included into others (example, & and &&), and

3条回答
  •  终归单人心
    2021-01-18 08:34

    Try this:

    String test = "a & b&&c=>d=A";
    String regEx = "(&[&]?|=[>]?)";
    
    String[] res = test.split(regEx);
    for(String s : res){
        System.out.println("Token: "+s);
    }
    

    I added the '=A' at the end to show that that is also parsed.

    As mentioned in another answer, if you need the atypical behaviour of keeping the delimiters in the result, you will probably need to create you parser yourself....but in that case you really have to think about what a "delimiter" is in your code.

提交回复
热议问题