The best way to check a string against many patterns

This is a question about best practices / design patterns than regular expressions.

In short, I have 3 values: from, to and the value I want to change. From must match one of several patterns:

XX.X >XX.X >=XX.X <XX.X <=XX.X XX.X-XX.X 

While To should be a decimal number. Depending on what value is set in From, I have to check if the value I want to change satisfies the From condition. For example, user inputs "From:> 100.00 To: 150.00" means that every value greater than 100.00 must be changed.

Regular expression itself is not a problem. The fact is that if I match the From integer with one regular expression and it passes, I still need to check which parameter was entered - this will lead to generating at least 5 IF in my code, and every time I want to add another option, I will need to add another IF - not cool. Same thing if I created 5 patterns.

Now I have a HashMap that contains a template as a key and ValueMatcher as a value. When a user enters a From value, I loop it against each key on this map, and if it matches, then I use the corresponding ValueMatcher to check if the value I want to change really matches the From value.

This approach, on the other hand, requires that I have a HashMap with all the features, a ValueMatcher interface and 5 implementations, each of which has only 1 short β€œmatch” method. I think this is better than IF, but still looks like an exaggerated solution.

Is there any other way to do this? Or is it how I really should do it? I really regret that we cannot store methods in HashMap / pass them as arguments, because then I will only have 1 class with all the appropriate methods and save them in HashMap.

+6
source share
2 answers

How about a chain of responsibility.

Each ValueMatcher object executes only one From / To rule and a link to the next ValueMatcher in the chain. Each ValueMatcher has a method that examines the candidate and either transagulates it or passes it to the next one in the chain.

Thus, adding a new rule is a trivial extension, and the control code simply passes the candidate to the first member of the chain.

+2
source

ValueMatcher interface and 5 implementations, each of which contains only one short β€œmatch” method. I think this is better than IF, but still looks like an exaggerated solution.

Well, for something as simple as estimating a number against an operator and a limit value, could you just write a slightly more general ValueMatcher that has a limit value and an operator as parameters? Then it would be pretty easy to add 5 instances of this ValueMatcher with several combinations of>,> =, etc.

EDIT: deleted non-Java files ... sorry.

0
source

Source: https://habr.com/ru/post/895681/


All Articles