I cannot show all lexical analyzer results

Asked

Viewed 67 times

0

My teacher passed a paper on compilers. He wants me to do a Lexical Parser.

I managed to do a good part of the code, but I can’t show the result.
I’m a beginner in Java and I’m using Eclipse.

The result that the Teacher wants to appear (with any result, does not need to have an input.) :

Example:

Expression: "8 + 8 = 16"

Result: (The code will analyze if this entry is correct, if it is not will say error).

Digito: 8
Operator: +
Digito: 8
Equality: =
Digito: 16

My code:

**package lexico;**

import java.util.HashMap;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lexico {
    public static void main (String []args) {

        String code  = "59-8=51";
        int c = 0;


        Map<String, String> tokens = new HashMap<>();
            tokens.put("[0-9]+", "[Digito:]");
            tokens.put("[/+/-]+", "[Operador:]");
            tokens.put("[/=]+", "[Igualdade: ]");

        while(c < code.length()) {

            for(Map.Entry<String, String> entry : tokens.entrySet()) {

                Pattern verificador = Pattern.compile(entry.getKey());
                Matcher ve = verificador.matcher(code);


                if(ve.find() && ve.start() == c) {
                    System.out.println(entry.getValue() + ve.group());  
                    c = c + ve.group().length();
                }
            } 
        }
    }
}

The result of my code:

inserir a descrição da imagem aqui

1 answer

0


Before I answer and show you the code, I want to tell you that the code has comments that indicate why I added/modified your code. I hope everything is readable and understandable.

    String code  = "59-8-10=41"; // Modifiquei o texto de entrada com mais uma substração apenas para teste.
    int c = 0;


    Map<String, String> tokens = new HashMap<>();
        tokens.put("[0-9]+", "[Digito:]");
        tokens.put("[/+/-]+", "[Operador:]");
        tokens.put("[/=]+", "[Igualdade: ]");

    while(c < code.length()) {

        for(Map.Entry<String, String> entry : tokens.entrySet()) {

            Pattern verificador = Pattern.compile(entry.getKey());
            Matcher ve = verificador.matcher(code).region(c, code.length()); // Indicar qual a região a analisar. Começa sempre no valor da variável c (já que esta tem qual o último index analisado) até ao comprimento da palavra de entrada.

            if(ve.find() && ve.start() == c) {
                System.out.println(entry.getValue() + ve.group());
                c += ve.group().length();
                break; // Quando o grupo deu match tens de sair do ciclo for para garantir que todas as expressões regulares são novamente percorridas para o novo grupo.
            }
        } 
    }
  • Blz bro. Helped a lot. Vlw

Browser other questions tagged

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