Вместо того, чтобы перебирать все ваши слова и проверять contains
для каждого из них каждый раз, когда пользователь вводит что-то, я бы предложил только цикл один раз, чтобы создать регулярное выражение для сопоставления, и использовать эту строку-регулярное выражение каждый раз, когда пользователь вводитчто-то.
Таким образом, ваш массив {"first", "top", "second", "third", "bottom"}
станет следующей строкой регулярного выражения:
"^.*(first|top|second|third|bottom).*$"
Это означает:
^ # Start looking at the start of the String
.* # Any amount of random characters (can be none)
(first|top|second|third|bottom)
# Followed by one of these words (the `|` are OR-statements)
.* # Followed by any mount of random characters again
$ # Followed by the end of the String
(^$
может бытьудаляется, если вы используете встроенный String#matches
, поскольку он всегда пытается неявно соответствовать всей заданной строке, но я бы добавил это как пояснение.)
После этого вы можете использовать это регулярное выражениекаждый раз, когда пользователь вводит что-то, используя userInput.matches(regex)
.
Здесь возможный тестовый код:
class Main{
public static void main(String[] a){
String[] array = {"first", "top", "second", "third", "bottom"};
// Create the regex-String of the array once:
String regex = "^.*(";
for(int i=0; i<array.length; i++){
regex += array[i];
if(i < array.length - 1) // All except for the last word in the array:
regex += "|";
}
regex += ").*$";
// Check all user inputs:
// TODO: Actually use user inputs instead of this String-array of test cases of course
for(String userInputTestCase : new String[]{"mine is the first one",
"its the one at the bottom",
"no match",
"top and bottom",
"first"}){
System.out.println(userInputTestCase + " → " + userInputTestCase.matches(regex));
}
}
}
В результате:
mine is the first one → true
its the one at the bottom → true
no match → false
top and bottom → true
first → true
Так что если один или несколько изслова из массива присутствуют / присутствуют, это приведет к true
(включая точные совпадения, как в последнем тестовом примере).
Попробуйте онлайн.
РЕДАКТИРОВАТЬ: Если вы хотите вместо строки матча, вы можете решитьd используйте слегка измененное регулярное выражение вместо Pattern.compile(regex).matcher(inputString)
:
Измените эти строки:
String regex = "("; // was `String regex = "^.*(";` above
...
regex += ")"; // was `regex += ").*$";` above
И добавьте следующее:
// TODO: Put the imports at the top of the class
// This is done once, just like creating the regex above:
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
// The following is done for every user input:
java.util.regex.Matcher matcher = pattern.matcher(userInputTestCase);
java.util.List<String> results = new java.util.ArrayList<>();
while(matcher.find()){
results.add(matcher.group());
}
System.out.println(userInputTestCase + " → " + results);
Попробуйте онлайн.