Regular expression problem (extracting one text or another)
I have problem with regex. I've been playing with it for three hours and I didn't find out anything working.
I have this开发者_JAVA技巧 text:
Fax received from 45444849 ( 61282370000 )
And I need to extract the number from brackets, so I will get 61282370000
. If there is nothing (or whitespaces only) in brackets it should take the number before brackets. I have only managed to do this expression, which takes the number from brackets correctly:
Fax received from .* \(\s([^)]*)\s\)$
Thanks.
Try the regex /(\d+)(?!\D*\d+)/ It uses negative lookahead to capture the last number in the string.
For eg.
perl -le '$_="Fax received from 45444849 ( 61282370000 )"; /(\d+)(?!\D*\d+)/; print $1'
will give you 61282370000. However,
perl -le '$_="Fax received from 45444849 ( )"; /(\d+)(?!\D*\d+)/; print $1'
gives 45444849 in $1
Pseudocode...
if str.match("\(\s*(\d+)\s*\)")
return str.matches("\(\s*(\d+)\s*\)")[0]
else
return str.matches("(\d+)")[0]
You should try to match on both... then use if
... assume the data is in $line
...
$line =~ /Fax\sreceived.+?(\d+)\s+\(\s*(\S+)?\s+\)/;
if ($2) {$result= $2;} else {$result= $1;}
Examples...
$line1 = "Fax received from 45444849 ( 61282370000 )";
$line1 =~ /Fax\sreceived.+?(\d+)\s+\(\s*(\S+)?\s+\)/;
if ($2) {$result= $2;} else {$result= $1;}
print "result1: $result\n";
$line2 = "Fax received from 95551212 ( )";
$line2 =~ /Fax\sreceived.+?(\d+)\s+\(\s*(\S+)?\s+\)/;
if ($2) {$result= $2;} else {$result= $1;}
print "result2: $result\n";
Running that yields...
[mpenning@Bucksnort ~]$ perl fax.pl
result1: 61282370000
result2: 95551212
[mpenning@Bucksnort ~]$
In Oracle PL/SQL, I should write as follows:
SELECT TRIM (
REPLACE (
REPLACE (
REGEXP_REPLACE (
'Fax received from 323 ( 123 )',
'[ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*( [0123456789]* )',
'',
1,
1,
'cm'),
')',
''),
'(',
''))
FROM DUAL;
The result of the SELECTed expression is 123.
If this is perl, you don't need to do the selection logic in the regex. You simply need to capture both and select, like so:
my $number = List::Util::first { $_; } m/(\d{7,})\s*[(]\s*(\d{7,})?\s*[)]/;
# deal with $number...
精彩评论