字符串:正则表达式用于替换操作



/*
* 2018年3月30日16:34:22
* 代码目的:
* 演示正则表达式用于替换操作。
* 方法见名知义。
* replaceFirst和replaceAll均为类Matcher的普通方法
* appendReplacement(StringBuffer sbuf,String replacement)执行渐进式的替换 。
* 这是一个非常重要的方法,它允许你调用其它方法生成或处理replacement,
* 使你能够以编程的方式将目标分割成组,从而具备更强大的替换功能
* */

//: strings/TheReplacements.java
import java.util.regex.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;

/*! Here's a block of text to use as input to
    the regular expression matcher. Note that we'll
    first extract the block of text by looking for
    the special delimiters,then process the
    extracted block. !*/
//上面的字符串是要处理的主体。
public class TheReplacements {
  public static void main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
    // Match the specially commented block of text above:
    Matcher mInput =
      Pattern.compile("/\\*!(.*)!\\*/",Pattern.DOTALL)
        .matcher(s);
    if(mInput.find())
      s = mInput.group(1); // Captured by parentheses
    // Replace two or more spaces with a single space:
  //单词之间如果有大于两个以上的空格,用单个空格替换
    s = s.replaceAll(" {2,}"," ");
    // Replace one or more spaces at the beginning of each
    // line with no spaces. Must enable MULTILINE mode:
    //使用模式标记,多行匹配,注意:^之后有一个空格,^表示一行开头。
    //+表示一个或多个。用一个空字符串替换。就是让多行的开始为为字。
    s = s.replaceAll("(?m)^ +","");
    print(s);
    s = s.replaceFirst("[aeIoU]","(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeIoU]");
    Matcher m = p.matcher(s);
    // Process the find information as you
    // perform the replacements:
    //逐个把字符串输入sbuf,如果匹配了正则表达式,把匹配的字符串转换
    //成大写输入sbuf
    while(m.find())
      m.appendReplacement(sbuf,m.group().toupperCase());
    // Put in the remainder of the text:
    //把结尾的没有匹配的字符串追加到sbuf中。
    m.appendTail(sbuf);
    print(sbuf);
  }
} /* Output:
Here's a block of text to use as input to
the regular expression matcher. Note that we'll
first extract the block of text by looking for
the special delimiters,then process the
extracted block.
H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO
thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll
first ExtrAct thE blOck Of tExt by lOOkIng fOr
thE spEcIAl dElImItErs,thEn prOcEss thE
ExtrActEd blOck.
*///:~

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...