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