集册 Java实例教程 返回在替换文本中引用组

返回在替换文本中引用组

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

497
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
返回在替换文本中引用组

import java.util.regex.Matcher;/*来自 n o w j a   v  a . c o m - 时  代  Java*/

import java.util.regex.Pattern;


public class Main {

  public static void main(String[] args) {

    String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";

    String replacementText = "($1) $2-$3";

    String source = "1111111111, 1111111, and 1111111111";


    // Compile the regular expression

    Pattern p = Pattern.compile(regex);


    // Get Matcher object

    Matcher m = p.matcher(source);
    /** from 
    N o w J a v a . c o m - 时代Java**/


    // Replace the phone numbers by formatted phone numbers

    String formattedSource = m.replaceAll(replacement
展开阅读全文