0

I want to strip out anything from a string that isn't a plus sign, or a minus, or a multiplication sign or a division sign (/).

So i thought I'd use RegEx and negative lookahead.

Given a Java array:

String[] operandsArray = str.split("(?!\\u002A|\\u002B|\\u002D|\\u002F).")

And a test string of 55+5, the resulting array operandsArray contains:

0:""
1:""
2:"+"

I'm looking for it to contain just the operands, so:

0:"+"

and given: 55+6-6*6/6, would return:

0:"+"
1:"-"
2:"*"
3:"/"

It should also match duplicates as well, so given 5+5+5+5, would return:

0:"+"
1:"+"
2:"+"

Can anyone help with this, thanks

8
  • 3
    It seems you just want to match and extract with [-+/*] regex. Commented Nov 3, 2021 at 16:54
  • @WiktorStribiżew Hi, using [-+/*] will strip out the operands and leave behind anything else, resulting in an array that, say given 55+5, would contain 55 and 5, I'm looking to do the opposite so that only * would remain Commented Nov 3, 2021 at 16:58
  • 2
    Remove everything which is not an operator and then split at each char: str.replaceAll("[^-+/*]","").split("") Commented Nov 3, 2021 at 17:00
  • @WhatTheWhat Did you seem the solution I linked to? Commented Nov 3, 2021 at 17:01
  • 1
    Do not use split, use Matcher#find as I showed in my top comment. Commented Nov 3, 2021 at 20:53

1 Answer 1

1

Use

import java.util.*;
import java.util.stream.*;
import java.util.regex.*;

class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String text = "55+6-6*6/6";
        String[] results = Pattern.compile("[+/*-]").matcher(text)
            .results()
            .map(MatchResult::group)
            .toArray(String[]::new);
        System.out.println(Arrays.toString(results)); 
    }
}

See Java proof.

Results: [+, -, *, /]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.