Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a dynamic way of building java regular expressions for patterns?

Tags:

java

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).

like image 447
awm Avatar asked Jan 27 '26 15:01

awm


1 Answers

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 valueFromFile so that you get the case insensitivity.

If you really do need regular expressions, uses matches instead of contains.

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).

like image 145
Dan McGrath Avatar answered Jan 29 '26 06:01

Dan McGrath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!