将当前字符串与文本文件进行比较 Java

Comparing current string to text file Java

我想知道是否有办法将字符串与文本文件进行比较以获得最佳答案。 例子: 我们在文本文件中有一个:

BANANA
BANTER
APPLE
BASKET
BASEBALL

并且当前字符串是:B.N...(点是未知字符)。有没有办法立即从文本文件中获取包含可能字母(如 A、T 和 E)的数组或哈希图?

我认为我应该做的: 我已经设法将文本文件的每一行都放在数组列表中。我应该将当前字符串与 arraylist 中的可能答案进行比较,并将该单词中的每个字符放在点的位置并将其放入新的 arraylist 中。

提前致谢。

您可以尝试使用正则表达式。您当前的字符串 "B.N..." 必须翻译成一个模式,您将把它与文本文件中出现的其他词相匹配。您可以找到有关正则表达式的教程 here.

这是一个小例子:

public class RegexPlayground {
    public static void main(String[] args){
        Pattern pattern=Pattern.compile("B.N...");
        String word="BANANA";
        Matcher matcher = pattern.matcher(word);
        if(matcher.find()){
            System.out.println("Found matching word \""+word+"\"");
        }
        word="BASKET";
        matcher = pattern.matcher(word);
        if(matcher.find()){
            System.out.println("Found matching word \""+word+"\"");
        }else{
            System.out.println("No match on word \""+word+"\"");
        }
    }
}

输出:

Found matching word "BANANA"

No match on word "BASKET"

所以程序的整体逻辑应该是这样的:

String regex = getRedex(); // This is your B.N...
Pattern pattern = Pattern.compile(regex);
List<String> words=readFromFile(); // The list of words in the text file
for(String word: words){
    Matcher matcher = pattern.matcher(word);
    if(matcher.find()){
        // Match found
        // do what you need to do here
    }else{
        // Same here
    }
}