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
    
    以下是在字符串中搜索特定单词的示例。
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Main {
       public static void main(String[] args) {
          String s1 = "sairamkrishna mammahe JC2182 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