微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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



/*
* 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.
*///:~

原文地址:https://www.jb51.cc/regex/357561.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐