pattern.compile java_Java Pattern compile(String)用法及代码示例
Java中Pattern類的thw compile(String)方法用于根據(jù)作為參數(shù)傳遞給方法的正則表達(dá)式創(chuàng)建模式。每當(dāng)您需要將文本與正則表達(dá)式模式進(jìn)行多次匹配時,請使用Pattern.compile()方法創(chuàng)建一個Pattern實例。
用法:
public static Pattern compile(String regex)
參數(shù):此方法接受一個單個參數(shù)regex,它代表編譯為模式的給定正則表達(dá)式。
返回值:此方法返回從正則表達(dá)式編譯的模式作為參數(shù)傳遞給該方法。
異常:此方法引發(fā)以下異常:
PatternSyntaxException:如果表達(dá)式的語法無效,則拋出此異常。
以下示例程序旨在說明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
總結(jié)
以上是生活随笔為你收集整理的pattern.compile java_Java Pattern compile(String)用法及代码示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将中文括号变为英文括号
- 下一篇: 三星手机安装linux系统下载,技术|在