查找

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

406
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用正则表达式以及appendReplacement()和appendTail()方法进行查找和替换

import java.util.regex.Pattern;

import java.util.regex.Matcher;
/**
时 代 J     a    v  a - nowjava.com 提供 
**/


public class Main {

  public static void main (String[] args) {

    String regex = "\\b\\d+\\b";

    StringBuffer sb = new StringBuffer();

    String replacementText = "";

    String matchedText = "";


    String text = "A test test 125 test test this is a test" + 

              " the value is 100 test test. " + 

              "This is a test." ;


    Pattern p = Pattern.compile(regex);

    Matcher m = p.matcher(text);/** 来 自 nowjava.com - 时  代  Java**/


    while (m.find()) {

      matchedText = m.group();


      // Convert the text into an integer for comparing

      int num = Integer.parseInt(matchedText);


      // Prepare the replacement text

      if (num == 100) {

        replacementText = "a hundred";

      }

      else if (num < 100) {

        replacementText = "less than a hundred";

      }

      else {

        replacementText = "more than a hundred";

      }


      m.appendReplacement(sb, replacemen
展开阅读全文