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

Pattern matching 2

Status
Not open for further replies.

fortytwo

Technical User
Apr 18, 2000
206
GB
Hi,

I have the following text:
[tt]
<input name=email value=&quot;name@hostname.com&quot; size=50 maxlength=50>
[/tt]

and I want to get the email address out of it into a variable. I am using the following regex:
[tt]
$text =~ m/.+<input name=email value=\&quot;(.+\@.+\..+)\&quot; size=50 maxlength=50>.+/;
print &quot;$1\n&quot;;
[/tt]
it does find the email address, but is there a neater way of doing thi, say on one line?

Will.

fortytwo
 
Is this what you want?

$text = '<input name=email value=&quot;name@hostname.com&quot; size=50 maxlength=50>';
($email) = $text =~ m/email value=\&quot;(.+)\&quot;/;
print &quot;$email\n&quot;;
 
That should probably be a non-greedy match just to be safe

($email) = $text =~ m/email value=\&quot;(.+?)\&quot;/;
^

jaa
 
sorry, the arrow should be under the ? after the +

(.+)\&quot; will gobble up everything upto the last &quot; in the string. If there is another set of quotes in the string after the email address then you will get everything up to that last quote.

(.+?)\&quot; will match only up to the next &quot; which is what you want.

jaa
 
Cool, thanks for that. Just out of interest, what does the () around $email do:
[tt]
($email) = $text =~ m/email value=\&quot;(.+?)\&quot;/;
[/tt]
What do they signify?

Will
fortytwo
will@hellacool.co.uk
 
The () around $email put the match in list context.
In list context everything captured by capturing (), such as the (.+?) above, is returned. So a match such as /(\w+)=(\w+)/
would return a list containing the two values it found.
ex.
$_ = &quot;key1=value1&quot;;

($val) = /(\w+)=(\w+)/;
# $val = key1
@vals = /(\w+)=(\w+)/;
# @var = (&quot;key1&quot;,&quot;value1&quot;)
%vals = /(\w+)=(\w+)/;
# $vals{key1} = value1

But
$val = /(\w+)=(\w+)/;
# $val = 1
I though it returned the number of times it matched (like s///) or the number of capturing () but it appears to only return 1 if sucessful and an empty string if it doesn't match.

jaa


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top