Search code examples
javaregexreplaceall

Java Regex - remove remaining portion of sting after a math operator


I need a regular expression that will remove the remaining characters after an operator. User passes in an equation, ex 55-6 OR 55+6 OR ( * / ).

Just need a regex that reads until one of those characters are hit, and remove the rest.

Ive got the divide '/' figured out: x = input.replaceAll("/[^/]*$", ""); I try following this same convention, but it doesnt work.

I looked at some of the other questions, but they all rely on knowing the specific character. In this case, I dont know what operator the user will pass in.

Thanks in advance.


Solution

  • This works:

    x = input.replaceAll("[-|\\+|\\*|/].*$", "");
    

    this expression looks for a '-' OR '+' OR '' OR '/', then removes everything after with the .$ the | pipe is used to separate values.

    the + and * characters actually mean something with regex, so the \ must be used before to show that you want the character itself.

    Hopefully the detailed solution helps