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
The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
Use re. fullmatch() to check whether the whole string matches a regular expression pattern or not.
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.
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).
\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With