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

在正则表达式中使用组

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

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

import java.util.regex.Pattern;

import java.util.regex.Matcher;


public class Main {
/*来自 
 时 代 J a v a - N o w J a v a . c o m*/

  public static void main(String[] args) {

    // Prepare regular expression. A group of 3 digits followed by 7 digits.

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

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

    

    // Compile the regular expression 

    Pattern p = Pattern.compile(regex);


    // Get Matcher object

    Matcher m = p.matcher(source);


    // Start matching and display the found area codes

    while(m.find()) {/** 来 自 时 代 J     a    v  a - nowjava.com**/

      // Display the phone number and area code. 

      // group 1 captures first 3 digits of match, 

      // whereas group 0 will have the entire phone number. 

      // The matched text can be obtained using m.group() or m.group(0)

      
展开阅读全文