Chinaunix首页 | 论坛 | 博客
  • 博客访问: 925921
  • 博文数量: 146
  • 博客积分: 3321
  • 博客等级: 中校
  • 技术积分: 1523
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-29 10:32
文章分类

全部博文(146)

文章存档

2014年(2)

2013年(5)

2012年(4)

2011年(6)

2010年(30)

2009年(75)

2008年(24)

分类: LINUX

2010-08-11 21:28:21

正则表达式(总结)
一:正则表达式是一种功能强大的文本处理语言,他的优势是:灵活,高效,强大,便捷。它的主要思想是一种描述字符串结构模式的形式化表达语言。他将字符串拆分成各种结构化的组合
二:首先用两个简单的例子程序看看正则表达式是如何工作的。
       例一:编写并测试方法static String replace(String str ,String str1, String str2),方法将第一个参数str中出现的所有单词str1用str2替换。
     import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class t1 {
            static String replace(String str,String str1,String str2){
              String regex0="\\b";    //这里解决了regex的格式问题 \b在正则表达式中表示单词分隔符
              String regex2=regex0+str1+regex0;  
              //String regex=str1;
              Pattern p=Pattern.compile(regex2);  //用于将给定的正则表达式regex2编译成一个模式
              Matcher m=p.matcher(str); //创建一个正则匹配器,该匹配器会将给定的字符串str与模式p匹配
              if(m.find()){   // 尝试查找与该模式匹配的输入序列的下一个子序列,如果找到返回true
                return str.replaceAll(regex2,str2);  //将str中的str1用str2替换
              }
              else
              {
                     return "there have no the word you want to replace!";                        
               }
           }
           public static void main(String[] args) {
             String str0="abc  i am you grand0_mother!abcabcab";
         String str1="i am your ?[}{mother!";
         String result;
        
         result=replace(str0,"b","abc");  // 这里希望将str0中出现的单词b用单词abc替换
         System.out.println("before replace: "+str0);
         System.out.println("after replaced: "+result);

         result=replace(str0,"mother","father"); //这里希望将str0中出现的单词mother用father替换
        System.out.println("berore replace: "+str0);
        System.out.println("after replace: "+result);

         result=replace(str1,"mother","father");//这里希望将str0中出现的单词mother用father替换
         System.out.println("before replace: "+str1);
         System.out.println("after replaced: "+result);
         System.out.println(str1);   // 输出str1
        }
}


程序运行结果:
str0 before replace: b i am you grandmother!abcabcab   
after replaced: abc i am you grandmother!abcabcab  //注意str0开始的b被替换为abc但后边出现的b并没有//被替换这是因为系统认为后边abcabcab中的b不是独//的单词
str0 berore replace: b i am you grandmother!abcabcab //这是用father替换单词mother同样因为grandmother中的mother不是单独的单词
after replace: there are not the word you want to replace!

str1 before replace: i am your ?[}{mother!
after replaced: i am your ?[}{father!  //这里单词mother被替换为了father
i am your ?[}{mother!  //这里输出替换后的str1但str1并没有改变说明用正则替换后原来的字符串并没有改变

注意:如果要将str0中出现的字符b全部替换为abc只需将源程序中的regex2改为被我注释掉的regex即可。程序执行结果将变为:
str0 before replace: b i am you grandmother!abcabcab
after replaced: abc i am you grandmother!aabccaabccaabc

str0 berore replace: b i am you grandmother!abcabcab
after replace: b i am you grandfather!abcabcab

str1 before replace: i am your ?[}{mother!
after replaced: i am your ?[}{father!
i am your ?[}{mother!
    这个程序如果用我们的一般方法解决的话替换字符还比较容易,但要是替换单词的话就会比较困难,因为单词的左右两侧可以使任意的字符我们都需要考虑到 比如上例的str1:i am your ?[}{father!单词father的左右两侧是非单词字符{和!。这用正则表达式完成的话只需要加一个\b即可完成。

三:这则表达式的用途
(1)           验证:在一些注册类网页上往往需要输入邮箱,姓名的内容这就需要我们判断用户的输入是否合法这事就可以用到正则表达式。
(2)           查找:最著名的要数unix下的sed编辑器,因为他是unix的主要发明者Ken Thompose用正则表达式完成的。这一事正则表达式的第一个应用程序。
(3)           替换。
四:正则表达的组成:由普通字符以及特殊字符组成。所谓普通字符就是所有的那些为显式指定的字符和非打印字符,也就是a-z ,0-9,及所有的标点喝一些其他字符。
      非打印字符如:\f(换页符),\n(换行符),\s(空白符)等等。
五:正则表达式的完整模型构建:
1.        首先将正则表达式转换为模式的编译版本的Pattern对象,
这就用到方法compile
public static
[url=mk:@MSITStore:F:\电子书\java\j2se\JDK_API_1_6_zh_CN.CHM::/java/util/regex/Pattern.html]Pattern[/url]
compile(
[url=mk:@MSITStore:F:\电子书\java\j2se\JDK_API_1_6_zh_CN.CHM::/java/lang/String.html]String[/url]
regex)
将给定的正则表达式编译到模式中。
参数:
regex - 要编译的表达式
抛出:
PatternSyntaxException
- 如果表达式的语法无效
public static
Pattern
compile(String regex, int flags)
将给定的正则表达式编译到具有给定标志的模式中。
抛出:
IllegalArgumentException
- 如果在 flags 中设置与定义的匹配标志不对应的位值
PatternSyntaxException
- 如果表达式的语法无效

2.       向Pattern对象请求一个Matcher对象,这个Matcher对象将模式应用到特定的字符串上。
3.       最后请求该Matcher对象用编译过的模式在者个字符串上进行操作。
故正则表达式典型的调用顺序是
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

六:是我的另一个例子:(也是我们曾经做过的一道题)
例二:定义一个FileSpec类,该类实现对一个文件标识符(含盘符、路径、和文件名)的包装,软件接口如下:
       public class FileSpec{
           public FileSpec(String spec)  //构造方法
           public String getName();
           public String getExtension();
           public String getPath();   
}
类中的三个方法分别用于获取被包装的文件名的基本名,扩展名和文件所在的路径(含盘符)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class filespec {
          public String filespec;
          public boolean flag;
public String regex2="(?i)[a-z]:[\\\\][^:?*\"|/]+[\\\\]([^:\"?*|/]+[^.])[.]([a-z]+)(?=\\b)";
          filespec(String filespec){
          this.filespec=filespec;
          flag=filespec.matches(regex2);  //首先检验输入的路径是否符合规范,如果符合则flag为true
         }
         public String getName(){
                    Pattern p=Pattern.compile(regex2);  //用于将给定的正则表达式regex2编译成一个模式
                    Matcher m=p.matcher(filespec);    //创建一个正则匹配器,该匹配器会将给定的字符串str与模式p匹配
                    if(m.find()){
                            return m.group(1);
                   }
                   return  "not";
         }
         public String getExtension(){
                    Pattern p=Pattern.compile(regex2);
                    Matcher m=p.matcher(filespec);
                   if(m.find()){
                            return m.group(2);
                   }
                   return "not";
         }
         public String getPath(){
                    Pattern p=Pattern.compile(regex2);
                    Matcher m=p.matcher(filespec);
                   if(m.find()){
                            return m.group(0);
                   }
                   return "not";
         }
}
public class T6_2_3{
   public static void main(String[] args){
            
            filespec file=new filespec("e:\\dsf\\df\\ggh.txt.java");
            if(file.flag){
                      String name=file.getName();
                      String path=file.getPath();
                      String extensionname=file.getExtension();
                     
                      System.out.println("Filepath: "+path);
                      System.out.println("Filename: "+name);
                      System.out.println("Extensiionname: "+extensionname);
            }
            else{
                      System.out.println(file.filespec);
                      System.out.println("illeagle path!");
            }
   }
}
该程序执行结果:

Filepath: e:\dsf\df\ggh.txt.java
Filename: ggh.txt
Extensiionname: java
 
 
这时我很久以前总结的,之前在博客上被窝误删了,今天浏览cu的时候才找到重新发一下。
阅读(2365) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~