How can I do this more intelligently and without conflict?

Asked

Viewed 83 times

0

In this way, it is returning some errors and it seems that it may present conflicts in the cases of 2-character operators.

Example: "++" being replaced by "#++#" while the next replaceAll() it will replace the operands of "#++#" 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("#");
}
  • The goal is to go from ++ for ##+##+## ? And if it is <= or ] would look like ?

1 answer

0


Regular Expression

For the replacement part, use a regular expression to do the replace. When programming the expression, place the double sequences first and then the simple 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 #]# #)# 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.