- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 应用程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 实用资源
- Java - 快速指南
- Java - 实用资源
使用 Java 在字符串中搜索特定单词的方法
问题说明
如何在字符串中搜索特定单词?
解决方案
以下示例演示了如何借助正则表达式中的 Matcher.start() 方法在字符串中搜索特定单词。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.compile("j(ava)");
String candidateString = "This is a java program. This is another java program.";
Matcher matcher = p.matcher(candidateString);
int nextIndex = matcher.start(1);
System.out.println(candidateString);
System.out.println("The index for java is:" + nextIndex);
}
}
结果
上述代码示例将生成以下结果。
This is a java program. This is another java program. The index for java is: 11
以下是一个在字符串中搜索特定单词的示例。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String s1 = "sairamkrishna mammahe Tutorials Point Pvt Ltd";
String regex = "\\bPoint\\b";
Pattern p1 = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m1 = p1.matcher(s1);
while (m1.find()) {
System.out.print("Start index: " + m1.start());
System.out.print(" End index: " + m1.end() + " ");
System.out.println(m1.group());
}
}
}
上述代码示例将生成以下结果。
Start index: 32 End index: 37 Point
java_regular_exp.htm
广告