pattern.compile java_Java Pattern compile(String)用法及代码示例

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

用法:

public static Pattern compile(String regex)

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

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

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

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

示例2:

// 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 = "brave";

// creare the string

// in which you want to search

String actualString

= "Cat is cute";

// compile the regex to create pattern

// using compile() method

Pattern pattern = Pattern.compile(REGEX);

// check whether Regex string is

// found in actualString or not

boolean matches = pattern

.matcher(actualString)

.matches();

System.out.println("actualString "

+ "contains REGEX = "

+ matches);

}

}

输出:

actualString contains REGEX = false


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