Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression /(ab)?use/: Is a more complex expression worth it?

Tags:

regex

perl

I'm writing a simple Perl script that translates assembly instruction strings to 32-bit binary code.

I decided to handle translation grouping instruction by type (ADD and SUB are R-Type instructions and so on...) so in my code I'm doing something like this:

my $bin = &r_type($instruction) if $instruction =~ /^(?:add|s(?:ub|lt|gt))\s/;

because I want to handle add, sub, slt and sgt in the same way.

I realized however that maybe using that regular expression could be an 'overkill' for the task I'm supposed to do... could the pattern

/^(?:add|sub|slt|sgt)\s/

represent a better use of regular expressions in this case?

Thanks a lot.

like image 786
dave Avatar asked Jul 07 '11 16:07

dave


People also ask

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"

What does AB mean in regular expression?

If a and b are regular expression, a + b is also a regular expression with language {a,b}. If a and b are regular expression, ab (concatenation of a and b) is also regular. If a is regular expression, a* (0 or more times a) is also regular.

What is the best use case for a regular expression?

Regular expressions are useful in search and replace operations. The typical use case is to look for a sub-string that matches a pattern and replace it with something else. Most APIs using regular expressions allow you to reference capture groups from the search pattern in the replacement string.

How do you give a regular expression?

Example : The regular expression ab+c will give abc, abbc, abbc, … and so on. The curly braces {…}: It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket.


1 Answers

Unless you are using a perl older than 5.10, the simple alternation will perform better anyway (see here), so there is no reason to try to optimize it.

like image 119
ysth Avatar answered Sep 28 '22 09:09

ysth