如何搜索字符串中的特定单词?(How to search a particular word in a string?)
优质
小牛编辑
124浏览
2023-12-01
问题描述 (Problem Description)
如何搜索字符串中的特定单词?
解决方案 (Solution)
下面的示例演示了如何在regex.Matcher类的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);
}
}
结果 (Result)
上面的代码示例将产生以下结果。
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 xnip 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