Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 992
Ondřej Holman Avatar asked May 10 '11 09:05

Ondřej Holman


1 Answers

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

like image 115
kshenoy Avatar answered Oct 13 '22 00:10

kshenoy