Regex with modifiers in variable?

F

fishfry

How do I match a regex when the regex is stored in a variable, and has
modifiers? Example:

$string = 'abcdefg';
$regex = 'def';

if ($string =~ $regex) {
print "yes\n";
}

prints "yes".

However

$string = 'abcdefg';
$regex = 'DEF';

if ($string =~ $regex) {
print "yes\n";
}

of course does not print yes.

But

$string = 'abcdefg';
$regex = '/DEF/i';

if ($string =~ $regex) {
print "yes\n";
}

does not print yes either.

Any suggestions?
 
G

Gunnar Hjalmarsson

fishfry said:
How do I match a regex when the regex is stored in a variable, and
has modifiers? Example:

$string = 'abcdefg';
$regex = '/DEF/i';

if ($string =~ $regex) {
print "yes\n";
}

does not print yes

One way is to move the modifiers, if possible:

$string = 'abcdefg';
$regex = 'DEF';

if ($string =~ /$regex/i) {
print "yes\n";
}
 
D

Darren Dunham

fishfry said:
How do I match a regex when the regex is stored in a variable, and has
modifiers? Example:
$string = 'abcdefg';
$regex = 'def';

Notice this example doesn't have the delimiters around the regex.
$string = 'abcdefg';
$regex = '/DEF/i';

But in this one you tried to put them in.

You'll have more luck with embedding the modifier into the regex itself.

% perldoc perlre
[...]
"(?imsx-imsx)"
One or more embedded pattern-match modifiers.
[...]
$pattern = "foobar";
if ( /$pattern/i ) { }

# more flexible:

$pattern = "(?i)foobar";
if ( /$pattern/ ) { }

So for your example, try
$regex = '(?i)DEF';
 
B

Bob Walton

fishfry wrote:

....
But

$string = 'abcdefg';
$regex = '/DEF/i';


$regex = qr/DEF/i;

if ($string =~ $regex) {
print "yes\n";
}

does not print yes either.

Any suggestions?


Use the qr// operator to define regexp you wish to assign to scalars.
That's what it's for. See:

perldoc perlop

particularly the section on "Regexp Quote-Like Operators".
 
F

fishfry

Bob Walton said:
fishfry wrote:

...


$regex = qr/DEF/i;




Use the qr// operator to define regexp you wish to assign to scalars.
That's what it's for. See:

perldoc perlop

particularly the section on "Regexp Quote-Like Operators".

Hey that works!! Thanks much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,814
Members
47,359
Latest member
Claim Bitcoin Earnings. $

Latest Threads

Top