Search code examples
javaregexreplaceall

Java - Parse an input with ReplaceALL expression


I trying to get an input to format a certain way. For example input:

Before:

"12/4"

I need a space after each letter in the string.

After:

" 12 / 4 "

Another example:

Before

"-10/-4*5"

After

" -10 / -4 * 5 "

Before

6*-8/(-4+2) 

After

 6 * -8 / ( -4 + 2 ) 

I use the spacing to parse and split the input but if theirs not spacing then I can't split by space.


Solution

  • We can assume that + or - is not unary when there is digit or expression in parenthesis before it. Rest of operators, like * / ^ can't be unary so they always should be surrounded with spaces.

    Using above assumptions you can create something like

    String text = "-10/-4*+5+6+(1*2)-3^2";
    String formatted = text.replaceAll("(?<=[\\d)])[-+]|[*/^]", " $0 ");
    
    System.out.println(formatted);
    

    Output:

    -10 / -4 * +5 + 6 + (1 * 2) - 3 ^ 2
    ^^^   ^^   ^^                        these are not changed
    

    Explanation: we want to surround with spaces only non-unary operators so

    • (?<=[\\d)])[-+] - we are checking if before - or + there is any digit or ) using look-behind (?<=[\\d)])
    • [*/^] we accept any of *, /, ^ as non-unary symbols which need to be surrounded by spaces - you can add here more symbols if you like for example ( ).
    • " $0 " - here $0 represents match from group 0 (match from entire regex) so we are simply replacing operator found by regex with the same operator but surrounded with spaces.