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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值