我对正则表达式有问题。我已经玩了三个小时了,我没有发现任何有效的东西。
我有这段文字:
Fax received from 45444849 ( 61282370000 )
我需要从括号中提取数字,所以我会得到61282370000
.如果括号中没有任何内容(或只有空格),则应将数字放在括号前。我只设法做了这个表达式,它正确地从括号中获取数字:
Fax received from .* (s([^)]*)s)$
谢谢。
试试正则表达式/(\d+)(?!\D*\d+)/它使用负前瞻来捕获字符串中的最后一个数字。
例如。
perl -le '$_="Fax received from 45444849 ( 61282370000 )"; /(d+)(?!D*d+)/; print $1'
会给你61282370000。然而
perl -le '$_="Fax received from 45444849 ( )"; /(d+)(?!D*d+)/; print $1'
以 1 美元提供45444849
伪代码...
if str.match("(s*(d+)s*)")
return str.matches("(s*(d+)s*)")[0]
else
return str.matches("(d+)")[0]
您应该尝试在两者上匹配...然后使用if
...假设数据在$line
...
$line =~ /Faxsreceived.+?(d+)s+(s*(S+)?s+)/;
if ($2) {$result= $2;} else {$result= $1;}
例子。。。
$line1 = "Fax received from 45444849 ( 61282370000 )";
$line1 =~ /Faxsreceived.+?(d+)s+(s*(S+)?s+)/;
if ($2) {$result= $2;} else {$result= $1;}
print "result1: $resultn";
$line2 = "Fax received from 95551212 ( )";
$line2 =~ /Faxsreceived.+?(d+)s+(s*(S+)?s+)/;
if ($2) {$result= $2;} else {$result= $1;}
print "result2: $resultn";
运行产生...
[mpenning@Bucksnort ~]$ perl fax.pl
result1: 61282370000
result2: 95551212
[mpenning@Bucksnort ~]$
在Oracle PL/SQL中,我应该这样写:
SELECT TRIM (
REPLACE (
REPLACE (
REGEXP_REPLACE (
'Fax received from 323 ( 123 )',
'[ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*( [0123456789]* )',
'',
1,
1,
'cm'),
')',
''),
'(',
''))
FROM DUAL;
SELECTed 表达式的结果是 123。
如果这是perl,则无需在正则表达式中执行选择逻辑。您只需要捕获两者并进行选择,如下所示:
my $number = List::Util::first { $_; } m/(d{7,})s*[(]s*(d{7,})?s*[)]/;
# deal with $number...