tags:

views:

89

answers:

2
set phoneNumber 1234567890

this number single digit, i want divide this number into 123 456 7890 by using regexp. without using split function is it possible?

A: 
my($number) = "8144658695";

$number =~ m/(\d\d\d)(\d\d\d)(\d\d\d\d)/;

my $num1 = $1;
my $num2 = $2;
my $num3 = $3;

print $num1 . "\n";
print $num2 . "\n"; 
print $num3 . "\n";  

This is writen for Perl and works assuming the number is in the exact format you specified, hope this helps.

This site might help you with regex http://www.troubleshooters.com/codecorn/littperl/perlreg.htm

Graeme Smyth
Overlooked the *tcl* tag?
Joey
oops lol, not doing well today, will go check that it works in TCL as well then
Graeme Smyth
with Perl, you should check that the match actually succeeded before you start using $1, $2, etc
glenn jackman
+6  A: 

The following snippet:

regexp {(\d{3})(\d{3})(\d{4})} "8144658695" -> areacode first second

puts "($areacode) $first-$second"

Prints (as seen on ideone.com):

(814) 465-8695

This uses capturing groups in the pattern and subMatchVar... for Tcl regexp

References


On the pattern

The regex pattern is:

(\d{3})(\d{3})(\d{4})
\_____/\_____/\_____/
   1      2      3

It has 3 capturing groups (…). The \d is a shorthand for the digit character class. The {3} in this context is "exactly 3 repetition of".

References

polygenelubricants
Please down downvote for suggesting the `->` variable name. I got that from what I assume is an official authoritative documentation for idiomatic Tcl. Then again this is CW (for some reason?) so feel free to edit and improve any way you can.
polygenelubricants
Using the "->" dummy variable name is fairly common for regexp, since it 1) shows that you're not using that information, and 2) just looks nice (ie, kindof reads as "goes into").
RHSeeger
+1 for the answer, where to get more info and explanation of the answer in that order. If I could I would give another +1 for the pretty formatting and concise, clear language.
slebetman
Be aware; if you're working with international phone numbers the way you break things up into groups varies at the country level. And in fact below that level too (e.g., the UK has area codes for land-lines only, not mobile numbers, and the prefix numbers determine the structure of the following numbers; area codes are of variable length).
Donal Fellows
@ polygen thanks,i get example from http://cheminfo.informatics.indiana.edu/~rguha/class/2007/i211/week13/hw13.html, and i try that solution of that regular expression using singel regexp
Prime