集册 Java实例教程 使用模式和匹配器类

使用模式和匹配器类

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

435
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用模式和匹配器类

import java.util.regex.Pattern;/** 来 自 时   代     Java  公  众  号 - nowjava.com**/

import java.util.regex.Matcher;


public class Main {

  public static void main(String[] args) {

    String regex = "[abc]@.";


    String source = "cric@mypkg.com is a valid email address";

    Main.findPattern(regex, source);


    source = "asdf@mypkg.com is invalid";

    Main.findPattern(regex, source);


    source = "a@asdf@fdsa@u";

    Main.findPattern(regex, source);


    source = "There is an @ sign here";

    Main.findPattern(regex, source);

  }


  public static void findPattern(String regex, String source) {
  /*
  nowjava
  */

    // Compile regex into a Pattern object

    Pattern p = Pattern.compile(regex);


    // Get a Matcher object

    Matcher m = p.matcher(source);


    boolean found = false ;


    // Print regex and source text

    System.out.println("\nRegex:" + regex);

    System.out.println("Text:" + source);


    // Perform find

    while (m.find()) {

      System.out.println("Matched Text:" + m.group() + ", Start:" + m.start() + ", " + 

                         
展开阅读全文