[英]How do I search a string for a keyword, then print whatever comes after that keyword in java?
我想搜索一個特定單詞的字符串,然后在該單詞之后打印接下來的5個字符。 我不知道該怎么辦。 我嘗試搜索教程,但找不到任何東西。
您可以在String上使用indexOf方法,然后為之后的字符做子字符串。
int start = yourString.indexOf(searchString);
System.out.println(yourString.subString(start + 1, start + 6);
您可以使用Matcher
和Pattern
使用正則表達式輕松完成此操作
import java.util.regex.*; //import
public class stringAfterString { //class declaration
public static void main(String [] args) { //main method
Pattern pattern = Pattern.compile("(?<=sentence).*"); //regular expression, matches anything after sentence
Matcher matcher = pattern.matcher("Some lame sentence that is awesome!"); //match it to this sentence
boolean found = false;
while (matcher.find()) { //if it is found
System.out.println("I found the text: " + matcher.group().toString()); //print it
found = true;
}
if (!found) { //if not
System.out.println("I didn't find the text."); //say it wasn't found
}
}
}
此代碼在單詞句子后查找並打印任何內容。 代碼中的注釋說明了它是如何工作的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.