[Java]一段尚未雕琢的分词代码

package com.hy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Entry {
    public static void main(String[] args) throws IOException{
        // 取得用户输入的表达式
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        System.out.print("请输入需要分词的文本:"); 
        String rawExpression = br.readLine(); 
    
        Lexer l=new Lexer(rawExpression);
    }
}
package com.hy;

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

// 分词器
public class Lexer {
    public Lexer(String expression) {
        String regex="\s*((//.*)|([0-9]+)|("(\\\\\"|\\\\\\\|\\\\n|[^\"])*")"
                       +"|[A-Z_a-z][A-Z_a-z0-9]*|==|<=|>=|&&|\|\||\p{Punct})?";
        
        Pattern pattern=Pattern.compile(regex);
        Matcher matcher=pattern.matcher(expression);
        matcher.useTransparentBounds(true).useAnchoringBounds(false);
        
        int pos=0;
        int end=expression.length();
        
        while(pos<end) {
            matcher.region(pos, end);
            
            if(matcher.lookingAt()) {
                if(matcher.group(1)!=null) {
                    System.out.print("1."+matcher.group(1));
                    
                    if(matcher.group(2)!=null) {
                        System.out.print(" 2."+matcher.group(2));
                        
                        if(matcher.group(3)!=null) {
                            System.out.print(" 3."+matcher.group(3));
                        }
                    }
                }
                
                System.out.println();
                
                pos=matcher.end();
            }
        }
    }
}

输出:

请输入需要分词的文本:int a=108;// 人数
1.int
1.a
1.=
1.108
1.;
1.// 人数 2.// 人数

请输入需要分词的文本:select a,b,c from tb1 where a='1' order by b desc
1.select
1.a
1.,
1.b
1.,
1.c
1.from
1.tb1
1.where
1.a
1.=
1.'
1.1
1.'
1.order
1.by
1.b
1.desc

请输入需要分词的文本:1+2*(4-3)-5
1.1
1.+
1.2
1.*
1.(
1.4
1.-
1.3
1.)
1.-
1.5

诸位看官莫怪,一时没来得及收拾。

原文地址:https://www.cnblogs.com/heyang78/p/11465788.html