I’m converting a perl program to java. In the perl script a value that is read from a file is checked against hundreds of regex patterns. I would like not to do this statically as it’s been done in the original perl program. Is there any sort of design pattern that can be used to make this more dynamic?
This is a single line of the current code:
$flag++ if ($Part_Name =~ /(harmonic|nsg|white\ sands|sphix|battery|collection|allied)/i);
Now repeat that for another 50-60 lines and that’s how many there are. The unique strings that are being tested against are in fact stand alone, all we care at the end is if ($flag > 0).
It doesn’t look like you actually need to use regular expressions.
Just create an array of what you are checking for (eg, “harmonic”, “white sands”) and loop over the array doing a contains:
valueFromFile.contains(arrayItem)If it matches, set a flag and exit. Don’t forget to lowercase
valueFromFileso that you get the case insensitivity.If you really do need regular expressions, uses
matchesinstead ofcontains.Note: There is probably a way to do this without explicitly without looping over the array, but I haven’t written Java for awhile (If there is, feel free to edit).