Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

match a part of a string

Status
Not open for further replies.

jamsman

Technical User
Jul 22, 2005
38
DE
hi all
i have a string and i need to see if a word appears in it

cheers
i expect this to be very easy and simple but its only a monday and im still asleep :)

cheers
 
ok....

# define a string (scalar) variable
$a_string = 'Hello World';

# does the string contain the word 'Hello' in it?
if($a_string =~ /Hello/){
[tab]print "It does!\n";
} else {
[tab]print "It doesn't :-(\n";
}

Mike

You cannot really appreciate Dilbert unless you've read it in the
original Klingon.

Want great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Oh Mike, ishnid'll be after you!

Code:
# define a string (scalar) variable
$a_string = 'Hello World';

# does the string contain the word 'Hello' in it?
if( [blue]index( $a_string, 'Hello' ) >= 0[/blue] ) {
    print "It does!\n";
} else {
    print "It doesn't\n";
}

Why use [tt]index()[/tt] rather than regexes? Three reasons:

1. It's the right tool for the job. Regexes are for matching patterns whereas this is just a straight search. This makes the intent of the programmer clearer which aids debugging and is a good thing.

2. It can be significantly faster.

3. Once incorporated into more complex code, it's unlikely that we'll just be looking for the pre-determined word 'Hello' - the second argument will probably be a variable. At that stage, we have to start worrying about quoting metacharacters or we'll get more than we bargained for (see multiple threads).

Yours,

fish

["]As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.["]
--Maur
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top