[英]Java: Check to see if String.contains matches exact word
嘗試檢查文本文件是否包含字符串,但是我只想要確切的字符串,例如。
String.contains(CA)。
但是讓我們說文本文件
什么是完全檢查“CA”的最佳方法,我只想為(1)返回true,但在我的情況下,我將為所有三個都得到真實。
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(Source)) {
hasSource = true;
break;
}
lineCounter++;
}
試試正則表達式:
Pattern re = Pattern.compile("\\bCA\\b",Pattern.CASE_INSENSITIVE);
Matcher m = re.matcher(text);
您可以使用正則表達式在另一個字符串中查找字符串,或者您甚至可以使用此方法:
//let's assume words are seperated by spaces only
for(String word: line.split(" ")) {
if(word.trim().equals(source))
//add your functionality
}
這假設您要搜索的單詞可以出現在該行的任何位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.