使用 find() 在 Java 正则表达式中查找子序列
find() 方法在输入序列中查找与所需模式匹配的子序列。此方法在 java.util.regex 包中 Matcher 类中提供。
下面的程序使用了 find() 方法在 Java 中查找子序列
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
Pattern p = Pattern.compile("cool");
Matcher m = p.matcher("Java is cool");
System.out.println("Subsequence: cool");
System.out.println("Sequence: Java is cool");
if (m.find())
System.out.println("
Subsequence found");
else
System.out.println("
Subsequence not found");
}
}输出
Subsequence: cool Sequence: Java is cool Subsequence found
现在让我们了解一下上面的程序。
在字符串序列“Java is cool”中搜索子序列“cool”。然后,使用 find() 方法查找输入序列中是否有该子序列,并打印所需的结果。如下面的代码片段所示:
Pattern p = Pattern.compile("cool");
Matcher m = p.matcher("Java is cool");
System.out.println("Subsequence: cool" );
System.out.println("Sequence: Java is cool" );
if (m.find())
System.out.println("
Subsequence found");
else
System.out.println("
Subsequence not found");
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP