zoukankan      html  css  js  c++  java
  • [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

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

  • 相关阅读:
    HDU 1847
    HDU 1717
    KMP未优化模板、
    Codeforces Round #340 (Div. 2) B. Chocolate
    HDU 1042 N!
    HDU 1018 Big Number
    HDU 1031 Design T-Shirt
    解决Windows 7删除执行过的 EXE、Bat文件有延迟的问题
    修改Android手机的“虚拟机堆大小”和android:largeHeap来防止APP内存溢出问题
    Android引用百度定位API第三方组件后导致其它.so文件无法正常加载的问题
  • 原文地址:https://www.cnblogs.com/heyang78/p/11465788.html
Copyright © 2011-2022 走看看