3

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

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm it's an interesting thought as I'm not 100% there are any specific regex checks in there. It's just a simple does this word appear anywhere in the string type check. Thanks.
Also, you might want to look into Groovy's support for Regular Expressions as a first class construct in the language. Groovy is a JVM language which syntactically is very similar to Java and is highly compatible with it. I mention this because a few Perl hacker friends swear by it when they're forced to do 'Java'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.