Equivalent to StringTokenizer with multiple characters delimiters

前端 未结 3 1432
你的背包
你的背包 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:35

    You can use the Pattern and a simple loop to achieve the results that you are looking for:

    List res = new ArrayList();
    Pattern p = Pattern.compile("([&]{1,2}|=>?| +)");
    String s = "s=a&=>b";
    Matcher m = p.matcher(s);
    int pos = 0;
    while (m.find()) {
        if (pos != m.start()) {
            res.add(s.substring(pos, m.start()));
        }
        res.add(m.group());
        pos = m.end();
    }
    if (pos != s.length()) {
        res.add(s.substring(pos));
    }
    for (String t : res) {
        System.out.println("'"+t+"'");
    }
    

    This produces the result below:

    's'
    '='
    'a'
    '&'
    '=>'
    'b'
    

提交回复
热议问题