集册 Java实例教程 正则表达式附加/替换

正则表达式附加/替换

欢马劈雪     最近更新时间:2020-01-02 10:19:05

481
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
正则表达式附加/替换
//from nowjava.com - 时  代  Java

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class Main {

  public static void main(String[] argv) {

    String input = "Thanks, thanks very much";

    String regex = "([Tt])hanks";

    Pattern pattern = Pattern.compile(regex);

    Matcher matcher = pattern.matcher(input);

    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {

      if (matcher.group(1).equals("T")) {

        matcher.appendReplacement(sb, "Thank you");

      } else {

        matcher.appendReplacement(sb, "thank you");

      }

    }

    matcher.appendTail(sb);

    System.out.println(sb.toString());

    sb.setLength(0);

    matcher.reset();/** n o w j a v a . c o m 提 供 **/

    String replacement = "$1hank you";

    while (matcher.find()) {

      matcher.appendReplace
展开阅读全文