Regular expression problem (extracting one text or another)

I have a problem with regex. I play with him for three hours, and I did not find anything.

I have this text:

Fax received from 45444849 ( 61282370000 ) 

And I need to extract the number from the brackets, so I will get 61282370000 . If there is nothing in brackets (or just spaces), it should take the number in front of the brackets. I managed to execute this expression that correctly takes the number from the brackets:

 Fax received from .* \(\s([^)]*)\s\)$ 

Thanks.

+6
source share
5 answers

Try the regular expression / (\ d +) (?! \ D * \ d +) / It uses a negative lookup to capture the last number in the string.

For instance,

 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

+9
source

You should try to match on both ... then use if ... suppose 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"; 

A launch that gives ...

 [ mpenning@Bucksnort ~]$ perl fax.pl result1: 61282370000 result2: 95551212 [ mpenning@Bucksnort ~]$ 
+1
source

PSEUDOCODE ...

 if str.match("\(\s*(\d+)\s*\)") return str.matches("\(\s*(\d+)\s*\)")[0] else return str.matches("(\d+)")[0] 
+1
source

In Oracle PL / SQL, I have to write the following:

 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.

+1
source

If it is perl, you do not need to do selection logic in the regex. You just need to take a picture and select, for example:

 my $number = List::Util::first { $_; } m/(\d{7,})\s*[(]\s*(\d{7,})?\s*[)]/; # deal with $number... 
+1
source

Source: https://habr.com/ru/post/887699/


All Articles