If you have a string stringA
containing your part number, you can use matches
on it like this:
stringB.matches(".*" + Pattern.quote(stringA) + ".*");
The reason for Pattern.quote
is that certain characters are special characters in a regular expression, and Pattern.quote
adds extra commands to the regex to make sure those characters are not treated as special. Letters and digits aren't special, though, so if you know that stringA
contains only letters and digits, you can skip Pattern.quote
:
stringB.matches(".*" + stringA + ".*");
If you have multiple strings that you want to check against, you could loop do the above match one part number at a time. Or you can join them all together like this:
stringB.matches(".*(3H0875AA|3J1127XQ|4X0078BA).*");
which will check for any of those part numbers. If you have an array of those strings, you can do this in Java 8:
String[] partNumbers;
stringB.matches(".*(" + String.join("|", partNumbers) + ").*");
if all the part numbers contain only letters and digits. Or you can use a stream to use Pattern.quote
and join everything together with |
:
stringB.matches(".*(" + Arrays.stream(partNumbers).map(Pattern::quote).collect(Collectors.joining("|")) + ").*");
Or in Java 7 you can construct a string using StringBuilder
and using a loop to append all the part numbers with Pattern.quote
and insert |
between the parts.