Split String In JAVA by specific words

前端 未结 2 449
灰色年华
灰色年华 2021-01-22 23:28

String S= \"multiply 3 add add 3 3 1\"

I want to get two string arrays The one is {\"multiply\", \"add\", \"add\"} Another out is {\"3\",\"3\",\"3\",1}

How can I

相关标签:
2条回答
  • 2021-01-23 00:06

    You should use Matcher instead of split:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    ...
    
    List<String> operators = new ArrayList<String>();
    Matcher m = Pattern.compile("add|multiply").matcher(s);
    while (m.find()) {
        operators.add(m.group());
    }
    
    List<String> operands = new ArrayList<String>();
    Matcher m = Pattern.compile("[0-9]+").matcher(s);
    while (m.find()) {
        operands.add(m.group());
    }
    
    0 讨论(0)
  • 2021-01-23 00:08

    You can use java 8 groupingBy.

    Map<Boolean, List<String>> map = Arrays
        .stream(s.split(" "))
        .collect(Collectors.groupingBy(e -> e.matches("\\d+")));
    
    System.out.println(map);
    

    The result is:

    {false=[multiply, add, add], true=[3, 3, 3, 1]}
    

    You can get operators and operands by:

    List<String> operators = map.get(false);
    List<String> operands = map.get(true);
    
    0 讨论(0)
提交回复
热议问题