How can I do this in a smarter way without conflict?

0

In this way, you are returning some errors and it looks like you may experience conflicts in cases of 2-character operators.

Example: "++" being replaced by "# ++ #" while on the next call of replaceAll() it will replace the operands from "# ++ #" to "## + ## + ##" ".

private String[] sliptBySpecialCharacteres(String lexeme) {

    return lexeme.replaceAll("==", "#==#")
                 .replaceAll("&&", "#&&#")
                 .replaceAll("=", "#=#")
                 .replaceAll(">", "#>#")
                 .replaceAll("++", "#++#")
                 .replaceAll("<=", "#<=#")
                 .replaceAll("!", "#!#")
                 .replaceAll("-", "#-#")
                 .replaceAll("--", "#--#")
                 .replaceAll("+", "#+#")
                 .replaceAll("+=", "#+=#")
                 .replaceAll("*", "#*#")
                 .replaceAll(",", "#,#")
                 .replaceAll(".", "#.#")
                 .replaceAll("[", "#[#")
                 .replaceAll("{", "#{#")
                 .replaceAll("(", "#(#")
                 .replaceAll(")", "#)#")
                 .replaceAll("}", "#}#")
                 .replaceAll("]", "#]#")
                 .split("#");
}
    
asked by anonymous 12.04.2018 / 07:51

1 answer

0

Regular Expression

For the replacement part, use a regular expression to make replace . When programming the expression, put the double sequences first and then the single ones.

A good place to test regular expressions is at RegExr .

Example:

public class MyClass {

    public static void main(String args[]) {

        String str = "uma * duas = 3 if 45 - 14 == 12 + ( 30 - 12 + [ 15 && 67 ] ) ";
        str = str.replaceAll("(##|[++]|--|[+]|&&|==|>|<|!|-|[+]|=|[*]|,|[.]|\{|\}|\[|\]|\(|\))", "#$1#");

        System.out.println(str);

    }
}

// resultado: uma #*# duas #=# 3 if 45 #-# 14 #==# 12 #+# #(# 30 #-# 12 #+# #[# 15 #&&# 67 #]# #)# 
    
12.04.2018 / 13:10