Question

I have the following list of part numbers from one of our vendors:

"3H0875AAAA0012"
"3H0875AABB0018"
"3H0875AAAC0010"

However, internally all of these part numbers are the same. I need to be able to compare the following part number: "3H0875AA" to the list above. Then the output should be three.

Something like:

stringB.matches(*stringA*); //where * means any character or characters before/after the string

The idea is that I can find all possible matches in a list of part numbers that contain the word "3H0875AA" in the string. I've tried to look into possible alternatives in regex but don't seem to understand it too good.

EDIT: The idea is to apply this concept to a large list of partNumbers. So I'm not sure on how to apply regex to a long list of partnumber rather than to a single partnumber as I mentioned in the example.

EDIT 2: Please see example below to confirm if its valid:

public void example(List<String> test, List<String> test2){

    for(String s: test){
        for (String s2: test2){
            if (s.matches("*."+s2+".*")){
                System.out.println("Match");
            }
        }
    }
}

Please advise

Was it helpful?

Solution

From the observation of your input, my suggestion will be to using this:

stringB.matches("3H0875AA.*");

But if you want to check the string to be anywhere, then you can use this:

stringB.matches(".*3H0875AA.*");

In the regex .* means any character(except \n) unlimited times.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top