Forum Moderators: coopster & phranque

Message Too Old, No Replies

         

pixel2003

12:47 pm on Apr 5, 2003 (gmt 0)



Hi,

I want to be able to take a string and remove everything that isn't one, two or three numbers followed by a percent sign.

So
"34854358% ddfoio" should NOT match
"am%sdjosk87d" should NOT match
but
"dsfsdkfjkjh77%" should match, and just leave me with "77%"
"fdkj dfds 453 df 5s51%" should leave me with "51%"

How can I do this in Perl?

Thanks
pixel

ShawnR

1:54 pm on Apr 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Pixel, and welcome to Webmaster World

Say $mystring contains your original string

$mystring =~ m/regular expresion/;

will match your regular expression

If parts of your regular expression are enclosed in parentheses () then $1 will contain the part of your string which matched, after the above statement has executed.

You can construct your regular expression as follows:

. matches any character

* modifies the previous part so that it matches 0 or more times. For example, .* matches any char zero or more times. i.e. any string of any length

? modifies the previous part so it matches as little as it can. For example, .*? matches as small a string as it can, given the next part of the regular expression.

\d matches any digit

{n,m} modifies the previous part so that it matches at least n times and not more than m times. For example, x{1,3}z will match the string 'xz', 'xxz' or 'xxxz'

That should give you enough to figure it out, but if you are feeling lazy, read on...

after
$mystring =~ m/.*?(\d{1,3}%)/;
$1 should contain your number, if there was a match. You can check that length($1) is not zero to check there was a match.

There are a few perl tutorials suggested in [webmasterworld.com ] if you are interested.

Shawn

Fischerlaender

4:15 pm on Apr 5, 2003 (gmt 0)

10+ Year Member



$_ = "dsfsdkfjkjh77%"; 
print $1 if(/[^0-9](\d{1,3}%)/);