• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Quick Perl question.

If I want to check if a string has an A and a B adjacent to each other, case and order not of importance, how do I accomplish this using regular expressions?

Acceptable choices are:
AB
Ab
bA
ba
Ba
...etc...
 
i believe it would be ...
m/ab|ba/i
or maybe with parenthesis, like:
m/(ab)|(ba)/i

not sure about that, but the i flag at the end is for case insensivity
 
Originally posted by: stndn
i believe it would be ...
m/ab|ba/i
or maybe with parenthesis, like:
m/(ab)|(ba)/i

not sure about that, but the i flag at the end is for case insensivity

Hmm... whenever I need to do something like that, I always put the pipe inside the parentheses. Something like m/(ab|ba)/i normally works for me. Either way, all of the stuff posted here should work fine. 🙂
 
Is there a "penalty" to using parenthesis in regular expressions in Perl? That is, can I throw them into my code for style purposes and not change the meaning of my regular expression?

Also, what is the different between (?:a|b) and (a|b). Thanks!
 
Originally posted by: moreDealsThanDS
Is there a "penalty" to using parenthesis in regular expressions in Perl? That is, can I throw them into my code for style purposes and not change the meaning of my regular expression?

Also, what is the different between (?:a|b) and (a|b). Thanks!

Well... yes and no on adding parentheses. Parentheses are mostly used to override precedence on different operators (5 + 3 * 2 gives a different result than (5 + 3) * 2, for example). But yeah, it's also a good idea to use parenthese to make code more readable. For instance:

a > b && a < c
gives the same result as
(a > b) && (a < c)

That's true because > and < have a higher precedence than &&. It gets even worse if you have more conditions in the same expression. Unless the person reading the code has memorized every operator's precedence, it could get pretty ugly unless there are parentheses in there. In short -- use parenthese to make code more readable, but make sure you don't change its meaning.

The ?: in (?:a|b) tells Perl that you want to backreference a. That just means that Perl will go back and search previously searched text. You probably wouldn't need to use that here, but it's useful if you're replacing text and don't want to end up with instances of things like "the the" and "is is" floating around.
 
Back
Top