Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: String.contains matches exact word

Tags:

In Java

String term = "search engines" String subterm_1 = "engine" String subterm_2 = "engines" 

If I do term.contains(subterm_1) it returns true. I don't want that. I want the subterm to exactly match one of the words in term

Therefore something like term.contains(subterm_1) returns false and term.contains(subterm_2) returns true

like image 357
VeilEclipse Avatar asked Aug 21 '14 02:08

VeilEclipse


People also ask

How do I check if a string contains a specific word in Java?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How do I check if a string has exact match?

Use re. fullmatch() to check whether the whole string matches a regular expression pattern or not.

Does Java contain regex?

String. contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

How do you match in Java?

Java - String matches() Method This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).


1 Answers

\b Matches a word boundary where a word character is [a-zA-Z0-9_].

This should work for you, and you could easily reuse this method.

public class testMatcher { public static void main(String[] args){      String source1="search engines";     String source2="search engine";     String subterm_1 = "engines";     String subterm_2 = "engine";      System.out.println(isContain(source1,subterm_1));     System.out.println(isContain(source2,subterm_1));     System.out.println(isContain(source1,subterm_2));     System.out.println(isContain(source2,subterm_2));  }      private static boolean isContain(String source, String subItem){          String pattern = "\\b"+subItem+"\\b";          Pattern p=Pattern.compile(pattern);          Matcher m=p.matcher(source);          return m.find();     }  } 

Output:

true false false true 
like image 173
JaskeyLam Avatar answered Oct 05 '22 00:10

JaskeyLam