1. 程式人生 > >Java如何找到一個單詞的每一次匹配?

Java如何找到一個單詞的每一次匹配?

lang 查找 dex 索引 匹配 imp static 一個 too

在Java編程中,如何查找字符串中特定單詞的最後一個索引?

以下示例演示如何使用Matlass類的matchet.find()方法和Pattern類的Patter.compile()方法查找字符串中指定詞組最後一個出現的索引。

package com.yiibai;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LastIndexWord {
   public static void main(String args[]) {
      String candidateString = "This is a Java example.This is another Java example.";
      Pattern p = Pattern.compile("Java");

      Matcher matcher = p.matcher(candidateString);
      matcher.find();
      int nextIndex = matcher.end();

      System.out.print("The last index of Java is:");
      System.out.println(nextIndex);
   }
}
Java

上述代碼示例將產生以下結果 -

The last index of Java is:14
Shell

示例-2

以下是另一個示例,用來計算字符串中指定單詞的最後一個出現的索引。

package com.yiibai;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LastIndexWord2 { 
   public static void main(String args[]) {
      String s1 = "Java is the one of best languagues, I like Java.";
      Pattern p1 = Pattern.compile("Java");

      Matcher m1 = p1.matcher(s1);
      m1.find();
      int nextIndex = m1.end();

      System.out.print("The last index is:");
      System.out.println(nextIndex);
   }
}
Java

上述代碼示例將產生以下結果 -

The last index is:4

Java如何找到一個單詞的每一次匹配?