user13394282
user13394282

Reputation:

Find the exact word using a regex or hashmap

I have the following 2 strings

String source1 = "Samsung Galaxy S10";
String source2 = "Samsung Galaxy S10+";

I tried by using pattern and matcher to get the exact value I want, but unfortunately without any success.

What I want to achieve is that, if I am searching for "Samsung Galaxy S10", it will only return to me source 1 without source2.

The opposite that if I am search for "Samsung Galaxy S10+", it will only returns the exact one, in this case is source2.

I want the solution to be more flexible not just for this specific example.

I have the idea as follow, but I don't know how to pass the correct pattern for this case.

private boolean isContain(String source) {
    String pattern = // NO IDEA; maybe something like \b[A-Z]\b I don't know. 
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(source);
    return m.find();
}

Upvotes: 0

Views: 154

Answers (2)

Pepe N O
Pepe N O

Reputation: 2344

Begins with ^ and ends with $, gives you exact match.

private static boolean isContain(String source) {
        String pattern = "^Samsung Galaxy S10$";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(source);
        return m.find();
}

Upvotes: 1

MC Emperor
MC Emperor

Reputation: 22977

Well, if you have a List and you are looking for an exact match, you could just use List::contains; so no need for using regular expressions.

If you want the match to be case-insensitive, you need to loop over the list and use String's equalsIgnoreCase method prior to comparing:

for (String item : list) {
    if (item.equalsIgnoreCase(searchTerm)) {
        return true;
    }
}
return false;

If the list of items is fairly large, then you're probably better off using a HashSet. The advantage of using a HashSet over a List is that a HashSet has a lookup time complexity of O(1). So calling HashSet::contains returns true if the set contains the given value. If you want to match case-insensitive, then make sure you call toLowerCase() on the String prior to adding it to the HashSet.

Note that a Set may not contain duplicate elements, but in this case, duplicates are pointless anyway.

Upvotes: 1

Related Questions