phone number backtracking

J

jtbutler78

I was wondering if anyone knew how to get the digits out of a phone
number where the area code is optional. I have a feeling that there
is backtracking involved but I am not sure. Anyone have any ideas?

This is what I have so far - it works for 10 digits not 7.
$phone = '123-123-1234';
$phone = '123-1234';

($area_cd,$prefix,$extension) = $phone =~ /(?<=(\d{3}) \-) (\d{3}) \-
(\d{4}) /x;
 
G

Gunnar Hjalmarsson

I was wondering if anyone knew how to get the digits out of a phone
number where the area code is optional. I have a feeling that there
is backtracking involved but I am not sure. Anyone have any ideas?

This is what I have so far - it works for 10 digits not 7.
$phone = '123-123-1234';
$phone = '123-1234';

($area_cd,$prefix,$extension) = $phone =~ /(?<=(\d{3}) \-) (\d{3}) \-
(\d{4}) /x;

What you tried is called a zero-width positive look-behind assertion. I
can't see why that would be needed; simple non-capturing parentheses and
the ? quantifier should do.

Try:

/(?:(\d{3})-)?(\d{3})-(\d{4})/;
 
J

jtbutler78

What you tried is called a zero-width positive look-behind assertion. I
can't see why that would be needed; simple non-capturing parentheses and
the ? quantifier should do.

Try:

/(?:(\d{3})-)?(\d{3})-(\d{4})/;

Thanks. I actually found something similar after I posted this. You
solution is better then the one I can up with.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top