集册 Java实例教程 在正则表达式中使用命名组

在正则表达式中使用命名组

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

567
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
在正则表达式中使用命名组

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class Main {/**来 自 n  o  w  j  a  v  a . c o m**/

  public static void main(String[] args) {

    // Prepare the regular expression

    String regex = 

      "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";

    

    // Reference first two groups by names and the thrd oen as its number

    String replacementText = "(${areaCode}) ${prefix}-$3";

    

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


    // Compile the regular expression

    Pattern p = Pattern.compile(regex);


    // Get Matcher object

    Matcher m = p.matcher(source);


    // Replace the phone numbers by formatted phone numbers
    /**
    来 自 时 代 J a v a 公 众 号
    **/

    String form
展开阅读全文