Java编程思想学习(十) 正则表达式

正则表达式是一种强大的文本处理工具,使用正则表达式我们可以以编程的方法,构造复杂的文本模式,并且对输入的字符串进行搜索.在我看来,所谓正则表达式就是我们自己定义一些规则,然后就可以验证输入的字符串是不是满足这些规则,主要的问题在于定义这些规则时要用到一些比较特别的语法,加大了理解的难度.以前就学习过一次java的正则表达式,但是学的模模糊糊的;主要的原因在于正则表达式的语法实在是很复杂,所以这次又去学习了正则的基本语法.其实在了解了正则表达式的基本语法后,学习java中的正则表达式还是很简单的.下面先介绍正则表达式的基本语法,然后再是java中的两种调用正则表示式的方式.

一.正则表达式的基本语法(内容转自网络) 
两个特殊的符号’^’和’$’。他们的作用是分别指出一个字符串的开始和结束。例子如下:

“^The”:表示所有以”The”开始的字符串(”There”,”The cat”等); 
“of despair$”:表示所以以”of despair”结尾的字符串;

“^abc$”:表示开始和结尾都是”abc”的字符串——呵呵,只有”abc”自己了; 
“notice”:表示任何包含”notice”的字符串。

象最后那个例子,如果你不使用两个特殊字符,你就在表示要查找的串在被查找串的任意部分——你并 
不把它定位在某一个顶端。

其它还有’*’,’+’和’?’这三个符号,表示一个或一序列字符重复出现的次数。它们分别表示“没有或 
更多”,“一次或更多”还有“没有或一次”。下面是几个例子:

“ab*”:表示一个字符串有一个a后面跟着零个或若干个b。(”a”, “ab”, “abbb”,……); 
“ab+”:表示一个字符串有一个a后面跟着至少一个b或者更多; 
“ab?”:表示一个字符串有一个a后面跟着零个或者一个b; 
“a?b+$”:表示在字符串的末尾有零个或一个a跟着一个或几个b。

你也可以使用范围,用大括号括起,用以表示重复次数的范围。

“ab{2}”:表示一个字符串有一个a跟着2个b(”abb”); 
“ab{2,}”:表示一个字符串有一个a跟着至少2个b; 
“ab{3,5}”:表示一个字符串有一个a跟着3到5个b。

请注意,你必须指定范围的下限(如:”{0,2}”而不是”{,2}”)。还有,你可能注意到了,’*’,’+’和 
‘?’相当于”{0,}”,”{1,}”和”{0,1}”。 
还有一个’¦’,表示“或”操作:

“hi¦hello”:表示一个字符串里有”hi”或者”hello”; 
“(b¦cd)ef”:表示”bef”或”cdef”; 
“(a¦b)*c”:表示一串”a”“b”混合的字符串后面跟一个”c”;

‘.’可以替代任何字符:

“a.[0-9]”:表示一个字符串有一个”a”后面跟着一个任意字符和一个数字; 
“^.{3}$”:表示有任意三个字符的字符串(长度为3个字符);

方括号表示某些字符允许在一个字符串中的某一特定位置出现:

“[ab]”:表示一个字符串有一个”a”或”b”(相当于”a¦b”); 
“[a-d]”:表示一个字符串包含小写的’a’到’d’中的一个(相当于”a¦b¦c¦d”或者”[abcd]”); 
“^[a-zA-Z]”:表示一个以字母开头的字符串; 
“[0-9]%”:表示一个百分号前有一位的数字; 
“,[a-zA-Z0-9]$”:表示一个字符串以一个逗号后面跟着一个字母或数字结束。

你也可以在方括号里用’^’表示不希望出现的字符,’^’应在方括号里的第一位。(如:”%[^a-zA-Z]%”表 
示两个百分号中不应该出现字母)。

为了逐字表达,你必须在”^.$()¦*+?{\”这些字符前加上转移字符’\’。 
请注意在方括号中,不需要转义字符。

二.使用String自带的正则表达式 
java的String类自带了一些正则表达式,我们可以通过一个String类对象很容易的使用正则表达式,具体如下: 
(1)matches()方法,参数是我们传入的正则表达式,如果整个字符串匹配成功则返回true否则返回false.如下面的代码所示:

 public class IntegerMatch {

     public static void main(String[] args){
///匹配一个可能为负的整数
System.out.println("-1234".matches("-?\\d+")); //下面的情况是+与\\d+匹配失败
System.out.println("+5678".matches("-?\\d+")); ///下面表达式表示可能一个加号或减号开头的整数
//因为加号+有特殊意义,所以要用\\进行转义
System.out.println("+5678".matches("(-|\\+)?\\d+"));
}/*Output
true
false
true
*/
}

(2).split()方法,我们传入一个正则表达式,它根据这个表达式将字符串分割成几个部分,返回一个String对象数组.它还有一个重载版本,还允许我们传入一个整数控制分割成几部分.如下面代码所示:

 import java.util.Arrays;

 ///spllit()是String类自带的一个正则表达式工具
///其功能是:将字符串重正则表达式匹配的地方切开成为一个个单词
///其实就是指定分隔符将字符串分成许多个单词(分隔符会消失),返回String数组
public class SplitTest { public static String knights="Then, when you have found the shrubbery, you must"
+"cut dwon the mightiest tree forest..."+"with... a herring";
public static void split(String regex){
System.out.println(Arrays.toString(knights.split(regex)));
} public static void main(String[] args){
split(" "); //用空格作为分隔符
split("\\W+"); ///非字母字符作为分隔符
split("n\\W+");///以n和非字母字符作为分隔符
}/*Output
[Then,, when, you, have, found, the, shrubbery,, you, mustcut, dwon, the, mightiest, tree, forest...with..., a, herring]
[Then, when, you, have, found, the, shrubbery, you, mustcut, dwon, the, mightiest, tree, forest, with, a, herring]
[The, whe, you have found the shrubbery, you mustcut dwo, the mightiest tree forest...with... a herring]
*/
}

(3)最后一个是”替换”,包括replaceFirst(),和replaceAll()两个函数,都需要我们传入一个正则表达式.两个的不同在于第一个函数只替换正则表达式第一个匹配的子串,而第二个会替换所有匹配的子串.如下面代码所示:

 package lkl;

 import java.util.Arrays;

 ///spllit()是String类自带的一个正则表达式工具
///其功能是:将字符串重正则表达式匹配的地方切开成为一个个单词
///其实就是指定分隔符将字符串分成许多个单词(分隔符会消失),返回String数组
public class RepalceTest { public static String knights="Then, when you have found the shrubbery, you must"
+"cut dwon the mightiest tree forest..."+"with... a herring";
} public static void main(String[] args){
///String类还只带了一个"替换"的正则表示式工具
///可以选择只替换第一个匹配的子串或替换所有匹配的地方 //将第一个以f开头并且后面至少有一个字符的子串替换成"located"
System.out.println(knights.replaceFirst("f\\w+", "located")); ///将字符串中含有的前三个子串替换成后面的字符串
System.out.println(knights.replaceAll("shrubbery|tree|herring","banana"));
}/*Output
Then, when you have located the shrubbery, you mustcut dwon the mightiest tree forest...with... a herring
Then, when you have found the banana, you mustcut dwon the mightiest banana forest...with... a banana */
}

三.使用regex包创建正则表达式 
上面通过String类使用正则的方式有一个很大的问题:我们写的正则表达式不能重复利用.实际上我们可以用Pattern类和Matcher类(这两个类都位于regex包下)构造更加强大的灵活的正则表达式.大概的步骤是:我们创建一个表示正则表达式的字符串,然后用static Pattern.compile()方法编译得到一个Pattern对象,然后将要我们要检索的字符串传入Pattern对象的matcher()方法,然后matcher()方法可以生成一个Matcher对象,这个Matcher对象有很多的功能可以调用.具体的过程就像下面这样:

 import java.util.regex.*;

 public class MatchTest {

     ///定义正则表示式数组,注意"\"要转义
public static String[] pattern ={"^Java","\\Breg.*","n.w\\s+h(a|i)s"
,"s?","s*","s+","s{4}","s{1}.","s{0,3}"};
//待匹配数组
public static String str="Java now has regular expressions";
public static void main(String[] args){
for(String pa : pattern){ //根据传入的String类型正则表达式,Pattern编译生成一个Pattern对象
Pattern p= Pattern.compile(pa); //将p对象与一个字符串关联生成一个Matcher对象
Matcher m =p.matcher(str);
System.out.println("正则表达式: \""+pa+"\" 在字符串上匹配: "+m.matches());
}/*Output
正则表达式: "^Java" 在字符串上匹配: false
正则表达式: "\Breg.*" 在字符串上匹配: false
正则表达式: "n.w\s+h(a|i)s" 在字符串上匹配: false
正则表达式: "s?" 在字符串上匹配: false
正则表达式: "s*" 在字符串上匹配: false
正则表达式: "s+" 在字符串上匹配: false
正则表达式: "s{4}" 在字符串上匹配: false
正则表达式:"s{1}." 在字符串上匹配: false
正则表达式:"s{0,3}" 在字符串上匹配: false
*/
}
}

Matcher对象包括了很多的可以调用的方法,包括与上面String类相同的matches(),split(),repalceFirst(), 
replaceFirst(),replaceAll()等方法,这些方法的用法和上面String类展示的是一样的.但是还有一些更加灵活的方法,如下面的代码所示.

 import java.util.regex.Matcher;
import java.util.regex.Pattern; //Matcher的find()方法可以查找到多个匹配
public class MatchFindTest { public static void main(String[] args){
///这个匹配的意思是:匹配字母
Matcher m=Pattern.compile("\\w+").matcher("Evening is full of"
+ "the linnet's wings");
while(m.find())
System.out.print(m.group()+" ");
System.out.println();
int i=0;
//这个重载的版本可以向里面传入一个参数,指定匹配的起点
while(m.find(i)){
System.out.print(m.group()+" ");
i++;
}
System.out.println();
}/*Output
Evening is full ofthe linnet s wings
Evening vening ening ning ing ng g is is s full full ull ll l ofthe ofthe ofthe fthe the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s
*/
}
 import java.util.regex.*;

 //lookingAt()判断该字符串的第一部分是否匹配
//group()方法可以将上次匹配成功的部分记录下来
//start()方法返回先前匹配的起始位置
//end()方法返回先前匹配的最后字符的索引加1的值
public class MatcherStartEnd { public static String str="This ais a example";
public static void main(String[] args){ Pattern p=Pattern.compile("\\w+is");
Matcher m=p.matcher(str);
System.out.print("longkingAt(): ");
if(m.lookingAt())
System.out.println(m.group()+" "+m.start()+" "+m.end()); m=p.matcher(str);
System.out.print("find(): ");
while(m.find()){
System.out.print(m.group()+" "+m.start()+" "+m.end()+" ");
}
System.out.println("");
}/*Output
longkingAt(): This 0 4
find(): This 0 4 ais 5 8 */
}
 import java.util.regex.Matcher;
import java.util.regex.Pattern; ///在调用Pattern的compile()函数时可以传入一些常量标记
///下面演示了两个最常用的常量表达式
public class ReFlags { public static void main(String[] args){
//Pattern.MULTILINE表示表达式^和$分别匹配一行的开始和介绍(默认匹配是整个字符串的开始和结束)
//Pattern.CASE_INSENSITIVE表示匹配时忽略大小写
Pattern p= Pattern.compile("^java",Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
Matcher m=p.matcher("java has regex\nJava has regex\n"+
"JAVA has pretty good regular expressions\n");
while(m.find()){
System.out.println(m.group());
}/*Output
java
Java
JAVA
*/
}
}
 import java.util.regex.*;

 ///Matcher对象的reset()方法可以将现有的Matcher对象应用于一个新的字符序列
///如果使用不带参数的rest()(不传入一个字符串),则表示将Matcher对象
//重新设置到当前字符序列的起始位置
public class Reset {
public static void main(String[] args){
Matcher m=Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");
while(m.find()){
System.out.print(m.group()+" ");
}
System.out.println();
m.reset("fix the rig with rags");
while(m.find()){
System.out.print(m.group()+" ");
}
System.out.println();
}/*Output
fix rug bag
fix rig rag
*/
}

转载:http://blog.csdn.net/acm_lkl/article/details/46473007

上一篇:Repository 返回 IQueryable?还是 IEnumerable?


下一篇:文字超出DIV的边框