手工分词稍嫌麻烦,不好维护,而利用正则表达式就利索多了。Java提供了java.util.regex.Matcher,java.util.regex.Pattern类来帮助我们实现此功能。
例一:以下程序将把"This is a farm that that raises dairy cattle."中的单词一个个找出来。
package com.hy; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RexTest { public static void main(String[] args){ String input = "This is a farm that raises dairy cattle."; String regExp = "(\\w+)"; Pattern pattern=Pattern.compile(regExp); Matcher matcher=pattern.matcher(input); while(matcher.find()){ System.out.println(matcher.group(0));// 在这里使用matcher.group(0)和matcher.group(1)效果是一样的 } } }
输出如下:
This
is
a
farm
that
raises
dairy
cattle
例二:以下程序将找出算术表达式中的数字和符号。由于算术表达式中的+-*/()在正则表达式里都有自己含义,如+表示一个或多个,因为需要直接表示符号本身时采用\\进行转义。
String input = "1+2+34*(5+78)/2"; String regExp = "(\\d+)|(\\+)|(\\-)|(\\*)|(\\/)|(\\()|(\\))"; Pattern pattern=Pattern.compile(regExp); Matcher matcher=pattern.matcher(input); while(matcher.find()){ System.out.println(matcher.group(0)); }
输出:
1 + 2 + 34 * ( 5 + 78 ) / 2
例三:在例二的基础上,增加小数的识别。正则表达式\\d+(\\.*)\\d*代表整数或者小数,如0.2,5,34.09都能识别出来。
String input = "1.1+0.2+34.09*(5+78)/0.0002"; String regExp = "(\\d+(\\.*)\\d*)|(\\+)|(\\-)|(\\*)|(\\/)|(\\()|(\\))"; Pattern pattern=Pattern.compile(regExp); Matcher matcher=pattern.matcher(input); while(matcher.find()){ System.out.println(matcher.group(0)); }
输出:
1.1 + 0.2 + 34.09 * ( 5 + 78 ) / 0.0002
例四:找出SQL语句中关键字,字段和条件
[A-Z_a-z][A-Z_a-z0-9]*表示以大小写字母或下划线开头之后可以是数字,字母,下划线之一
(=)*表示可以出现0个或一个等号
(\\')*表示出现0个或一个单引号
(\\')*\\w*(\\')*表示引号中间可以为字符
String input = "select field1,field2,field3 from table1 where field1='1' order by field2 "; String regExp = "([A-Z_a-z][A-Z_a-z0-9]*(=)*(\\')*\\w*(\\')*)"; Pattern pattern=Pattern.compile(regExp); Matcher matcher=pattern.matcher(input); while(matcher.find()){ System.out.println(matcher.group(0)); }
输出:
select field1 field2 field3 from table1 where field1='1' order by field2
--END--2019年9月3日09点50分