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