编程语言
首页 > 编程语言> > 词法分析程序的设计与实现

词法分析程序的设计与实现

作者:互联网

 词法分析程序(Lexical Analyzer)要求:

- 从左至右扫描构成源程序的字符流

-  识别出有词法意义的单词(Lexemes

-  返回单词记录(单词类别,单词本身)

-  滤掉空格

-  跳过注释

-  发现词法错误

 

程序结构:

输入:字符流(什么输入方式,什么数据结构保存)

处理:

–遍历(什么遍历方式)

–词法规则

输出:单词流(什么输出形式)

–二元组

 

单词类别:

1.标识符(10)

2.无符号数(11)

3.保留字(一词一码)

4.运算符(一词一码)

5.界符(一词一码)

单词符号

种别码

单词符号

种别码

begin

1

:

17

if

2

:=

18

then

3

<

20

while

4

<=

21

do

5

<>

22

end

6

>

23

l(l|d)*

10

>=

24

dd*

11

=

25

+

13

;

26

-

14

(

27

*

15

)

28

/

16

#

0

本案例使用Java编写解析器

 

package com.lzh.springbootstudytestcache;


import java.util.*;

/**
 * @author lzh
 * create 2019-10-09-21:13
 */
public class homework {

    public static HashMap<Integer,String> hashMap = new HashMap<Integer,String>();

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("请输入字符串");
        String str = sc.nextLine();
        parse(str);

    }

    public static void parse(String str){

        hashMap.put(0,"#");
        hashMap.put(1,"begin");
        hashMap.put(2,"if");
        hashMap.put(3,"then");
        hashMap.put(4,"while");
        hashMap.put(5,"do");
        hashMap.put(6,"end");
        hashMap.put(10,"l(l|d)*");
        hashMap.put(11,"dd*");
        hashMap.put(13,"+");
        hashMap.put(14,"-");
        hashMap.put(15,"*");
        hashMap.put(16,"/");
        hashMap.put(17,":");
        hashMap.put(18,":=");
        hashMap.put(20,"<");
        hashMap.put(21,"<=");
        hashMap.put(22,"<>");
        hashMap.put(23,">");
        hashMap.put(24,">=");
        hashMap.put(25,"=");
        hashMap.put(26,";");
        hashMap.put(27,"(");
        hashMap.put(28,")");

        String[] strArr = str.split(" ");

        //while end 32423 ffff =: >= fff(fsS) 44
        for (String s : strArr) {
            for (String s1 : strArr) {
                List<String> include = isInclude(s1);
                if (include.get(0) != "" || include.get(0) != null){
                    System.out.println(s1);
                } else {
                    System.out.println(include.get(0));
                }
            }
        }

    }

    public static List<String> isInclude(String str){
        String[] strTmp = {":=","<=","<>",">="};
        ArrayList<String> arrayList = new ArrayList();
        for (int i = 0; i < 5; i++) {
            int index = str.indexOf(strTmp[i]);
            if (index != -1){
                arrayList.add(0,str);
                str = str.replaceAll(":=|<=|<>|>=","");
                arrayList.add(1,strTmp[i]);
            } else {
                arrayList.add(0,"");
                arrayList.add(1,strTmp[i]);
            }
        }
        return arrayList;
    }
}

  

标签:单词,hashMap,arrayList,分析程序,词法,str,put,设计,String
来源: https://www.cnblogs.com/lzhdonald/p/11640788.html