Split String In JAVA by specific words

微笑、不失礼 提交于 2019-12-31 02:58:05

问题


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 get it? I tried to use

String operators[] = s.split("[0-9]+"); 
String operands[] =s.split("(?:add|multiply)");

But, it doesn't work.


回答1:


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());
}



回答2:


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);


来源:https://stackoverflow.com/questions/51681056/split-string-in-java-by-specific-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!