Fab*_*bio 0 string perl parsing http
我需要一些关于perl中字符串解析的帮助.我有一个http服务器响应这样的事情:
<html>
<head><title></title></head><body>
T:17.10;H:32.10
</body></html>
Run Code Online (Sandbox Code Playgroud)
我需要捕获这两个数字(在示例17.10和32.10中)并将它们放入两个变量中,我将用它来做一些if ... then ... else循环.
我在字符串操作和正则表达式方面不是那么专家,目前我还是要这样做:
my $url = 'http://192.168.25.9';
my $content = get $url;
die "Couldn't get $url" unless defined $content;
my @lines = split /\n/, $content;
$content2 = $lines[2];
$content2 =~ tr/T://d;
$content2 =~ tr/H://d;
my @lines2 = split /;/, $content2;
$tem = $lines2[0];
$hum = $lines2[1];
$tem =~ m{(\d+\.\d+)};
$hum =~ m{(\d+\.\d+)};
Run Code Online (Sandbox Code Playgroud)
但是当我打印出这条线时,我看到一些奇怪的东西:字符缺失,线条中的空间等等.似乎我有一些奇怪的隐形字符会造成混乱.
你能建议我在两个数字变量中使用两个数字的更好方法吗?
谢谢法比奥
一个完整的解决方案,避免使用REGEX解析HTML(ref:RegEx匹配除XHTML自包含标记之外的开放标记 ):
use strict; use warnings;
# base perl module to fetch HTML
use LWP::UserAgent;
# base perl module to parse HTML
use HTML::TreeBuilder;
# fetching part
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => "http://192.168.25.9");
my $res = $ua->request($req);
die $res->status_line, "\n" unless $res->is_success;
# parsing part
my $tree = HTML::TreeBuilder->new();
# get text from HTML
my $out = $tree->parse($res->decoded_content)->format;
# extract the expected string from the text output
if ($out =~ /^\s*T:(\d{2}\.\d{2});H:(\d{2}\.\d{2}).*/) {
print join "\n", $1, $2;
}
Run Code Online (Sandbox Code Playgroud)
17.10
32.10
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
670 次 |
| 最近记录: |