Java 正则表达式

    最近的编程中用到了正则表达式,在此顺便总结一下一直以来用到过的例子。

    正则表达式(Regular Expression,在代码中简写为 regex)。

    一、空白符

    在处理XML文件的时候遇到了麻烦,需要将XML中标记之间的空白去掉。即,将标记右尖括号和下一个标记的左尖括号之间的空白全部去掉,而其他位置的空白不需要处理。

    问题在于,空格的个数不是固定的,于是很自然地想到了正则表达式。

    代码如下:

  String oldStr = "<a> \n <b> \r </b> </a> \n < >";

  // \s匹配任意的空白符,包括空格,制表符(Tab),换行符,中文全角空格
  String regex = ">\\s+<";    // +:重复一次或者更多次;*重复零次或者更多次。
  String replacement = "><";
  String newStr = oldStr.replaceAll(regex, replacement);
  System.out.println(oldStr);
  System.out.println(newStr);

    运行结果:

  <a><b></b></a><  >

    二、字符串

    在此之前,同样是处理XML文件,也遇到过类似的匹配问题。

    一般情况下,读取XML模板文件,将其中的标记赋予相应的数值。例如:<age>%age%</age> => <age>18</age>

    然而,新的需求要求要上一个功能的逆操作。代码如下:

  String oldStr = "<Age>23aFs</age>";
  String regex =  "(?i)<age>[0-9a-z]*</age>";    // (?i):不区分字母大小写
  String replacement ="<Age>%Age%</Age>";
  String newStr = oldStr.replaceAll(regex, replacement);
  System.out.println(oldStr);
  System.out.println(newStr);

    运行结果:

  <Age>%Age%</Age>

    三、总结

    以前在遇到要用正则表达式的时候会想到Pattern和Matcher,后来发现可以直接用String中的replaceAll()方法。 

  // Replaces each substring of this string that matches the given regular expression with the given replacement.

  public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
  }

    和这个方法名称类似的一个方法replace():

  // Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. 

  public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
    this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
  }

    CharSequence是一个接口,在java.lang中;String类实现了这个接口。

posted @ 2014-08-23 23:22  Longzheyuan  阅读(272)  评论(0)    收藏  举报