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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern matching problem . . .

Status
Not open for further replies.

youthman

Programmer
Apr 28, 2004
49
US
I am trying to work on a script, and can seem to figure out how to do something that should be really simple.
I have a variable that contains text. I need to check to see if that text contains a specific bit of text, and if it does, do something else. For example:

$a="this is the image that goes with the information";

if ($a =~ "[IMG]") {
go do something else here
}
else{ ..continue on


The problem that I am getting is that it doesn't seem to work, and I feel like an idiot. I know that I probably am, since I am not a really experienced programmer, but can someone please help me?!?!?
There is no actual image, it has been stripped away from the variable, and it leaves the [IMG] tag there. That is what I am testing for. If it has the tag, then my program received the wrong data, and needs to keep looking.

Thank you in advance for your help!

 
Brackets [] are regular expression special characters that indicate a character class. This is probably not what you want in this instance, so each bracket should be escaped. Additionally, since that is a regex, I suggest that you use a regex operator. Here's how I would write that code:

Code:
[url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$string[/blue] = [red]"[/red][purple]this is the image [IMG] that goes with the information[/purple][red]"[/red][red];[/red]

[olive][b]if[/b][/olive] [red]([/red][blue]$string[/blue] =~ [red]m{[/red][purple][purple][b]\Q[/b][/purple][IMG][purple][b]\E[/b][/purple][/purple][red]}[/red][red])[/red] [red]{[/red]
	[gray][i]# go do something else here[/i][/gray]
	
[red]}[/red] [olive][b]else[/b][/olive] [red]{[/red]
	[gray][i]# ..continue on[/i][/gray]

\Q is a special escape code for the quotemeta function. You could just escape each character explicitly, but I prefer this method since it quickly indicates that the entire regex is intended to be constant.

Secondly, never use the variable name $a or $b. These are special variables used by the sort function. Save yourself some headache and just use $x, $y, $z.

- Miller
 
Thank you Miller! That worked GREAT! Yes, I know about $a and $b ... I just used $a here for simplicity. I thank you though. I knew it was something simple that I was just being an idiot on! :) Thank you again for your help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top