1

I have an Equation that includes Operator and Operand. I want to split it and extract the Operator and Operand in one String array like this:

4+3 -2 + 1* 5 -2

4,+,-,2,+,1,*,5,-,2

Does anyone have a suggested Regex pattern for this?

skobaljic
  • 9,379
  • 1
  • 25
  • 51
mmsamiei
  • 165
  • 1
  • 2
  • 10

2 Answers2

1

Here is a way to do it with regex, haven't used these much so might be able to be improved.

Pattern pattern = Pattern.compile("[0-9]+|(\\+|-|\\*)");
Matcher matcher = pattern.matcher("4+3 -2 + 1* 5 -2");
List<String> parts = new ArrayList<>();
while (matcher.find()) {
    parts.add(matcher.group());
}
String[] array = parts.toArray(new String[parts.size()]);
System.out.println(Arrays.toString(array));

Outputs:

[4, +, 3, -, 2, +, 1, *, 5, -, 2]
Bubletan
  • 3,833
  • 6
  • 25
  • 33
0

What you're trying to do is called tokenization. You shouldn't need a RegEx for this. You should be able to just use a StringTokenizer. The answers on this other SO post should suit your needs: String Tokenizer in Java.

Update

Although the original suggestion should suit your needs, it looks like the StringTokenizer class is bordering on deprecated.

From the javadocs:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Anyway, it is and option if you want to use it.

Community
  • 1
  • 1
Sildoreth
  • 1,883
  • 1
  • 25
  • 38