Perl正则表达式和替换 - URL字符串上的替换

时间:2015-09-02 14:40:46

标签: regex perl

嘿,我有关于Perl的基本问题。

我有这样的链接

my $url = "http://test.com/index.php?id=123&test=1&l=1";

我有三个值。我想要计算id并打开它。

页面不是静态的。因此基本URL可能会更改或查询参数。

  • 我需要像(*)?(*)=(*)&(*)这样的正则表达式,我想要计算每个参数中的数字。

  • 另一个问题是,我想将a添加到参数计数中,例如1a2a3a等,并为每个修改后的参数启动一些请求参数。

3 个答案:

答案 0 :(得分:4)

最好使用URI模块来操作网址

以下是从URL

的查询组件构建哈希<a href="#" on-click="fb_login">Sign in with facebook</a> 的示例

我不明白你的意思“我想算上id并打开它。”Polymer ({ is: 'facebook-login', fb_login: function() { FB.login( function( response ) { FB.api( '/me', function( facebookResponse ) { /* Do something here*/ }); }, { scope: 'public_profile,email,user_birthday' } ); }, ready: function() { window.fbAsyncInit = function() { FB.init({ appId: 'YOUR_APP_ID', cookie : true, xfbml: true, version: 'v2.3' }); }; if( typeof(FB) == 'undefined' ) { ( function( d, s, id ) { var js, fjs = d.getElementsByTagName(s)[0]; if ( d.getElementById( id ) ) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }( document, 'script', 'facebook-jssdk' ) ); } }, }); 参数的值在%query中,为123,但我无法想象计算它可能是什么

我只使用id来显示结果哈希的内容。在您的生产代码中没有必要

$query{id}

输出

Data::Dump


更新

听起来您想创建几个新的网址,并依次将use strict; use warnings; use URI; my $url = URI->new('http://test.com/index.php?id=123&test=1&l=1'); my %query = $url->query_form; use Data::Dump; dd \%query; 添加到每个查询参数的值

这是一个如何运作的例子

{ id => 123, l => 1, test => 1 }

输出

a

答案 1 :(得分:1)

我实际上是这样做的:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my $url = "http://test.com/index.php?id=123&test=1&l=1";

my %param = $url =~ m/(\w+)\=(\w+)/g;

print Dumper \%param;

如果您想为所有参数添加a

$url =~ s/(\w+=\w+)/$1a/g;

答案 2 :(得分:0)

匹配所有url参数并将每个参数名称和值捕获为每个匹配的第1组和第2组:

/(?<=[?&])(\w+)=(\w+)/

请参阅live demo

相关问题