Regular expressions when searching for string containing brackets or parans ..

J

Joe Halbrook

I am trying to search a string that may contain brackets or parenthesis.
Could someone suggest a way to do this such that the seacrh will not
fail, when the string search does contain the special character, i.e.

if ($searchstring =~ /$_/i) {

when $searchstring and $_ may contain a string with a [, ], (, or ) character?

Much thanks, in advance.

Joe Halbrook
 
T

Tedd Hansen

From the manual;
if ($searchstring =~ /\Q$_\E/i) {

it quotes the string correctly before processing the regex

- Tedd
 
T

Tad McClellan

[ please do not top-post. Text rearranged. ]




That's the "Quote and Quote-like Operators" section of the perlop manual.

Will this work even if $searchstring contains an "reserved"
character, or should I:

$newsearchstring =~ /\Q$searchstring\E/i)


Please use copy/paste with *real* code.

Was the parenthesis supposed to be a semicolon?

if ($newsearchstring =~ /\Q$_\E/i) {


Backslash escapes, such as \Q and \n, work in "double quotish" strings.

The match operator is "double quotish", but you can also use them in
actual double-quoted strings.

So, use one in a double-quoted string and then print the string
to see what it did:

my $searchstring = 'open paren(';
my $str = "\Q$searchstring";
print "$str\n";


See also the named function that does the same thing:

perldoc -f quotemeta
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top