Java Pattern compile(String)用法及代码示例

  • Post author:
  • Post category:java


Java中Pattern类的thw compile(String)方法用于根据作为参数传递给方法的正则表达式创建模式。每当您需要将文本与正则表达式模式进行多次匹配时,请使用Pattern.compile()方法创建一个Pattern实例。

Pattern构造器是私有的,不能通过new创建Pattern对象,可以通过Pattern调用静态方法compile返回Pattern实例。

定义

//将给定的正则表达式编译并赋予给Pattern类
public static Pattern compile(String regex) {
    return new Pattern(regex, 0);
}

参数:此方法接受一个单个参数regex,它代表编译为模式的给定正则表达式。

同上,但增加flag参数的指定,可选的flag参数包括:CASE INSENSITIVE,MULTILINE,DOTALL,UNICODE CASE, CANON EQ

返回值:此方法返回从正则表达式编译的模式作为参数传递给该方法。

异常:此方法引发以下异常:

PatternSyntaxException:如果表达式的语法无效,则抛出此异常。

以下示例程序旨在说明compile(String)方法:

示例1:

// Java program to demonstrate 
// Pattern.compile() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = ".*www.*"; 
  
        // creare the string 
        // in which you want to search 
        String actualString 
            = "www.geeksforgeeks.org"; 
  
        // compile the regex to create pattern 
        // using compile() method 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // get a matcher object from pattern 
        Matcher matcher = pattern.matcher(actualString); 
  
        // check whether Regex string is 
        // found in actualString or not 
        boolean matches = matcher.matches(); 
  
        System.out.println("actualString "+ "contains REGEX = "+ matches); 
    } 
}

输出:

actualString contains REGEX = true

二、例子

实例一


        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("22bb23");
        m.matches();//返回false,因为bb不能被\d+匹配,导致整个字符串匹配未成功. 
        Matcher m2 = p.matcher("2223");
        m2.matches();//返回true,因为\d+匹配到了整个字符串 

        m = p.matcher("22bb23");
        m.find();//返回true 
        m2 = p.matcher("aa2223");
        m2.find();//返回true 
        Matcher m3 = p.matcher("aa2223bb");
        m3.find();//返回true 
        Matcher m4 = p.matcher("aabb");
        m4.find();//返回false 

        m = p.matcher("22bb23");
        m.lookingAt();//返回true,因为\d+匹配到了前面的22 
        m2 = p.matcher("aa2223");
        m2.lookingAt();//返回false,因为\d+不能匹配前面的aa 

        m = p.matcher("aaa2223bb");
        m.find();//匹配2223 
        m.start();//返回3 
        m.end();//返回7,返回的是2223后的索引号 
        m.group();//返回2223 

实例二

        Pattern p = Pattern.compile("([a-z]+)(\\d+)");
        Matcher m = p.matcher("aaa2223bb");
        m.find();   //匹配aaa2223 
        m.groupCount();   //返回2,因为有2组 
        m.start(1);   //返回0 返回第一组匹配到的子字符串在字符串中的索引号 
        m.start(2);   //返回3 
        m.end(1);   //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置. 
        m.end(2);   //返回7 
        m.group(1);   //返回aaa,返回第一组匹配到的子字符串 
        m.group(2);   //返回2223,返回第二组匹配到的子字符串 



版权声明:本文为zhuying123jl原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。