Java 中的 Pattern toString() 方法以及示例
**java.util.regex** 包中的 Pattern 类是正则表达式的编译表示。
此类的 toString() 方法使用编译当前 Pattern 的正则表达式返回字符串表示。
示例1
import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "(\d)";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Printing the regular expression
System.out.println("Compiled regular expression: "+pattern.toString());
//Verifying whether match occurred
if(pattern.matcher(input).find())
System.out.println("Given String contains digits");
else
System.out.println("Given String does not contain digits");
}
}输出
Enter input string This 7est contain5 di9its in place of certain charac7er5 Compiled regular expression: (\d) Given String contains digits
示例 2
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "Tutorialspoint$";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(input);
int count = 0;
if(match.find())
System.out.println("Match found");
else
System.out.println("Match not found");
System.out.println("regular expression: "+pattern.toString());
}
}输出
Match found regular expression: Tutorialspoint$
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP