Regex to format 1234 to 1,234

P

pembed2003

Hi all,
I am trying to come up with a regex to format number like:

1234
-1234
1234567

to:

1,234
-1,234
1,234,567

The numbers will always be interger. So far, I have the following:

#1:

while(<>){
chomp;
$_ = reverse split //;
s/(\d{3})\B/$1,/g;
$_ = reverse split //;
print "$_\n";
}

#2:

while(<>){
chomp;
my $n = $_ =~ s/^-// ? '-' : '';
$_ = 'x' . $_ while(length($_) % 3);
s/(.{3})\B/$1,/g;
s/^[x,]+//;
print "$n$_\n";
}

#3:

while(<>){
chomp;
my $n = '';
while(s/\B(\d{3})$//g){
$n = ",$1" . $n;
}
$n = $_ . $n if length;
print "$n\n";
}

All three methods seems to be a bit too "long", is there a better way?
I am trying to do this as a way for me to learn regex so I would like
not to use a module if possible. Thanks!
 
T

Tad McClellan

pembed2003 said:
I am trying to come up with a regex to format number like:
1,234
-1,234
1,234,567


You are expected to check the Perl FAQ *before* posting to
the Perl newsgroup you know...


perldoc -q commas

How can I output my numbers with commas added?
 
P

pembed2003

Tad McClellan said:
You are expected to check the Perl FAQ *before* posting to
the Perl newsgroup you know...


perldoc -q commas

How can I output my numbers with commas added?

perldoc -a 'got it'

Thanks!
 
L

Lukas Mai

Purl Gurl schrob:
[...]
Although not all that efficient, beneath my signature ^^^^^^^^^^^^^^^^^^^^
is a sample of fun code from way back.
[...]

Isn't that impossible? AFAIK a signature is defined as m{^-- \n.*\z}sm,
so "beneath my signature" means "after the end of the article".

Confused, Lukas
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top