This situation sounds straight out of Match (or replace) a pattern except in situations s1, s2, s3 etc.
Compared with other potential solutions, the regex couldn't be simpler:
custom|onetomany|manytomany|atom|tomcat|tomorrow|automatic|(tom)
If you want to show not just tom
but the whole word it is in, such as tomahawk
, change this to:
custom|onetomany|manytomany|atom|tomcat|tomorrow|automatic|(\w*tom\w*)
The left side of the alternation matches the words you don't want. We will ignore these matches. The right side matches and captures tom
to Group 1, and we know they are the right tom
because they were not matched by the expressions on the left.
This program shows how to use the regex (see the results at the bottom of the online demo). It finds tom
and tomahawk
.
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject = "custom onetomany manytomany atom tomcat tomorrow automatic tom tomahawk";
Pattern regex = Pattern.compile("custom|onetomany|manytomany|atom|tomcat|tomorrow|automatic|(\\w*tom\\w*)");
Matcher regexMatcher = regex.matcher(subject);
List<String> group1Caps = new ArrayList<String>();
// put Group 1 captures in a list
while (regexMatcher.find()) {
if(regexMatcher.group(1) != null) {
group1Caps.add(regexMatcher.group(1));
}
} // end of building the list
System.out.println("\n" + "*** Matches ***");
if(group1Caps.size()>0) {
for (String match : group1Caps) System.out.println(match);
}
} // end main
} // end Program
Reference
How to match (or replace) a pattern except in situations s1, s2, s3...