Pattern Matching

Posted on 1998-12-28
Last Modified: 2010-03-05
How do I match a string for multiple characters?

$string = "sgds*G$GJ#G()g";

I want to search $string for any instances of * OR # OR $.

What's the easiest (best) way to do this?

Question by:tribal9
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 84

Expert Comment

ID: 1207184
Do you mean
$string = 'sgds*G$GJ#G()g';
or did you define $GJ
What do you want to do with any instances of * OR # OR $
To check if $string contains any of them, you might say:
print '$string contains instances of * OR # OR $' if $string =~ /[*#\$]/;
or perhaps:
$string =~ m'[*#$]'

Expert Comment

ID: 1207185
Is this what you want?

if ($string =~ /[\*\$#]/) {
  print "Found one!";
else {
  print "Sorry!";


Accepted Solution

comvosora earned 20 total points
ID: 1207186
Well, you can do a

@a = $string =~ /.*([#*$])+.*/gsi;

and get each occurence in one item of array @a (if you would like to count them, for instance)

Author Comment

ID: 1207187
Ah, yes, Martin and Ozo, that was what I wanted.

The $G in the string was a typo (meant just the '$' char, not variable), and I am using it to block out unacceptable names from a form submission.

LVL 84

Expert Comment

ID: 1207188
martinag's solution works, (although it's not neccessary to backwhack the * inside of a [] character class)
But the Accepted Answer does not work.
(and even with a \ in front of the $, the .* would mean it only gets the last occurance, contrary to comvosora's comment)

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question