Java搜索词组
如何在一个字符串搜索一个特定的词?
解决方法
下面的例子演示了如何在字符串中使用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); } }
结果
上面的代码示例将产生以下结果。
This is a java program. This is another java program. The index for java is: 11