2

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
  • 1
    You could start by splitting the string by spaces into a single array, then checking each element of the array to match specific patterns, to separate them into the two target arrays. Commented Aug 3, 2018 at 23:23

2 Answers 2

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()); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Your example regex is only using 1 group (1).
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.