我需要编写一个与3个稍微不同的字符串匹配的正则表达式,并从中提取值 字符串如下(不包括引号)
1. "Beds: 3, Baths: 3"
2. "Beds: 3 - Sleeps 10, Baths: 3"
3. "Beds: 3 - 10, Baths: 3"
为
提取的值1. 3, 0 , 3
2. 3, 10, 3
3. 3, 10, 3
我写过类似
的内容 $pattern = '/Beds: ([0-9]+).*-[ Sleeps]* ([0-9]+).* Baths: ([\.0-9]+)/';
它与字符串2和3匹配,但不与字符串1匹配。
答案 0 :(得分:5)
只需从非数字中提取数字。
\D*(\d+)\D*(\d+)?\D*(\d+)
答案 1 :(得分:0)
Beds: ([0-9]+)(?:(?:.*-[ Sleeps]* ([0-9]+))|).* Baths: ([\.0-9]+)
答案 2 :(得分:0)
#!/usr/bin/perl
use strict;
use warnings;
open (my $rentals, '<', 'tmp.dat');
while (<$rentals>){
if (my ($beds, $sleeps, $baths) = $_=~m/^Beds:\s+(\d+)(?:\s+-)?\s*(?:Sleeps\s+)?(\d+)?,\s+Baths:\s+(\d+)$/){
$sleeps=$sleeps?$sleeps:"No information provided";
print "$.:\n\tBeds:\t$beds\n\tSleeps:\t$sleeps\n\tBeds:\t$beds\n\n";
}
else{
print "record $. did not match the regex:\n\t|$_|";
}
}
答案 3 :(得分:-1)
检查一下:
'/Beds:\s(\d)[\s,][\s-].*?(\d, |)Baths:\s(\d)/'