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

前端之家收集整理的这篇文章主要介绍了字符串:正则表达式用于替换操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


/*
* 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.f2er.com/regex/357561.html

猜你在找的正则表达式相关文章