当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Regular expression to match three different strings

问题描述:

I need to write a regular expression that matches with 3 slightly different strings and extracts values out of them

Strings are as follows (excluding quotes)

1. "Beds: 3, Baths: 3"

2. "Beds: 3 - Sleeps 10, Baths: 3"

3. "Beds: 3 - 10, Baths: 3"

Values to extract like, for

1. 3, 0 , 3

2. 3, 10, 3

3. 3, 10, 3

I have written something like

 $pattern = '/Beds: ([0-9]+).*-[ Sleeps]* ([0-9]+).* Baths: ([\.0-9]+)/';

It matches with string 2 and 3, but not with string 1.

网友答案:

Just extract the digits from non-digits.

\D*(\d+)\D*(\d+)?\D*(\d+)
网友答案:
Beds: ([0-9]+)(?:(?:.*-[ Sleeps]* ([0-9]+))|).* Baths: ([\.0-9]+)
网友答案:
#!/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|$_|";
    }
}
网友答案:

check this:

'/Beds:\s(\d)[\s,][\s-].*?(\d, |)Baths:\s(\d)/'
分享给朋友:
您可能感兴趣的文章:
随机阅读: