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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
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…
Six Sigma Control Plans

691 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