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