Java:在String中获取匹配位置的方法?

hhh*_*hhh 127 java string match

String match = "hello";
String text = "0123456789hello0123456789";

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

pol*_*nts 249

执行此操作的方法系列包括:

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


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"
Run Code Online (Sandbox Code Playgroud)

  • @polygenelubricants - 您的"查找所有事件"示例都很聪明.但是,如果进行代码审查,您将获得有关代码可维护性的演讲. (4认同)
  • 你会怎么写的?我老实说,因为我之前没有专业的代码审查经验. (3认同)
  • lolz,刚刚在while循环中实现了一个赋值,然后你在for循环+1中发布了一个赋值 (2认同)

小智 39

这适用于正则表达式.

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));
}
Run Code Online (Sandbox Code Playgroud)

输出:

在指数2 - 5找到'爱'

一般规则 :

  • 正则表达式从左到右搜索,一旦使用了匹配字符,就无法重复使用.

  • 这很棒,但是对于这句话,我得到了输出"我有一个男朋友":-) (13认同)

Sur*_*gch 8

寻找单一指数

正如其他人所说,text.indexOf(match)用来寻找单一的比赛.

String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Run Code Online (Sandbox Code Playgroud)

查找多个索引

由于@ StephenC关于代码可维护性的评论以及我自己在理解@polygenelubricants的答案时遇到的困难,我想找到另一种方法来获取文本字符串中匹配的所有索引.以下代码(从此答案修改)执行此操作:

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

int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) {  // indexOf returns -1 if no match found
    System.out.println(index);
    index = text.indexOf(match, index + matchLength);
}
Run Code Online (Sandbox Code Playgroud)