Java:获取字符串中匹配位置的方法?

新手上路,请多包涵
String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?

原文由 hhh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 583
2 个回答

执行此操作的方法系列是:

返回此字符串中指定子字符串第一次( _或最后一次_)出现的索引 [从指定索引开始向前( _或向后_)搜索]。


 String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
    System.out.println(i);
} // prints "22", "13", "4"

原文由 polygenelubricants 发布,翻译遵循 CC BY-SA 3.0 许可协议

这适用于使用正则表达式。

 String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);

while (match.find()) {
     System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}

输出 :

在索引 2 - 5 找到“爱”

一般规则 :

  • 正则表达式从左到右搜索,匹配字符一旦被使用,就不能重复使用。

原文由 Aldwane Viegan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题