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
總結
以上是生活随笔為你收集整理的pattern.compile java_Java Pattern compile(String)用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将中文括号变为英文括号
- 下一篇: JAVA实现bmp转换JPEG_Java