I have a list of cities, want to search from these cities:
ArrayList myCities; // list of cities
String searchString = scanner.nextLine();
List<String> matchedCities = new ArrayList(); // an empty list for storing matched cities
for(String c : myCities){
if(c.matches("(?i)" searchString ".*")){
matchedCities.add(c);
}
}
eg. apple if it is an element in array currently c returns apple of if ap entered or apple but not for ppl.
This works only for if a city start with or start/initials, however I want if a user enter string from middles it should return the suggested city;
e.g. if a user enters ppl, it should return apple, or any word that has ppl whether if it starts with or contains in middles or ends with.
CodePudding user response:
String::matches
impicitly checks the entire string as if "^" and "$" anchors are applied, so a minor fix to check for a value in the middle would be to update the regex to allow any prefix ".*"
.
Also, it may be needed to put the searchString
between \Q
and \E
to enable search by string literal, and automatically escape characters which may be reserved for the regular expressions.
if (c.matches("(?i).*\\Q" searchString "\\E.*")){
matchedCities.add(c);
}
Another option would be to convert both searchString
and the element in the list to the same case and use contains
.
An example implementation using Stream API:
String search = searchString.toLowerCase();
List<String> matchedCities = cities
.stream()
.filter(c -> c.toLowerCase.contains(search))
.collect(Collectors.toList());