开发者

Extracting text in between strings in Perl

In Perl, how do I extract the text in a string if I knew the pre and post parts of the text?

Example:

Input: ww开发者_如何学编程w.google.com/search?size=1&make=BMW&model=2000

I would like to extract the word 'BMW' which is always in between "&make=" and the next "&"


Don't use a regular expression. Use URI and URI::QueryParam, like so:

use strict;
use warnings;
use URI;
use URI::QueryParam;

my $u = URI->new('http://www.google.com/search?size=1&make=BMW&model=2000');
print $u->query_param('make');


Use a Regular expression:

my ($captured_string) = $link =~ /\&make=(\w+)\&/;

My regex assumes that you would want to capture anything that appeared in the make field. \w captures upper and lower case letters. If you want to capture something else you can use a character class. Like this [\w\s]+ would match more than one letters and spaces. You can add anything between the [ ] of characters to match in any order.

The ( ) is what actually does the capturing. If you remove that then it will just match (and you should use it in an if statement. If you wanted capture more than one string (say you wanted the model as well. Based on your example you could use a second set of parenthesis like this:

my ($make, $model) = $link =~ /\&make=(\w+)\&model=([A-Za-z0-9]+)/;

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜