在Java编程中,如何在字符串中搜索指定的单词(子字符串)?
以下示例演示如何使用regex.Matcher
类的matcher.start()
方法来搜索字符串中的特定单词。
package com.yiibai;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SearchingWord {
public static void main(String args[]) {
String patternString = "java";
String candidateString = "This is a java program. This is another java program.";
// Matcher matcher = p.matcher(candidateString);
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(candidateString);
int count = 0;
while (matcher.find()) {
count++;
System.out.println("found: " + count + " : " + matcher.start() + " - " + matcher.end());
}
}
}
上述代码示例将产生以下结果 -
found: 1 : 10 - 14
found: 2 : 40 - 44
示例-2
以下是在字符串中搜索指定的单词(子字符串)的另一个示例。
package com.yiibai;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SearchingWord2 {
public static void main(String[] args) {
String s1 = "yiibai is one of best IT Yiibai website.";
String regex = "\\btutorials\\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: 25 End index: 34 Yiibai