2

我有一个像600000. 我想在每 2 位数字后插入空格。我该怎么做?结果应该是60 00 00

4

4 回答 4

7

If 12345 should become 12 34 5, I recommend

s/..(?!\z)\K/ /sg

The (?!\z) ensures that you don't add a trailing space.


If 12345 should become 1 23 45, I recommend

s/(?!^)(?=(?:..)+(?!.))/ /sg

(?!^) ensures you don't add a leading space.

This isn't very efficient. It might be more efficient to reverse the input, use the first solution, then reverse the output.

于 2013-01-29T20:05:49.650 回答
5

比较了几种不同的方法。我假设您不想修改原始字符串,否则 100% 正则表达式版本可能会做得更好。

#!/usr/bin/perl

use strict;
use warnings;

use Benchmark ();

my $x = "1234567890";

Benchmark::cmpthese(1_000_000, {
    unpack   => sub { join(" ", unpack("(A2)*", $x)) },
    regex    => sub { (my $y = $x) =~ s/..(?!\z)\K/ /sg; $y },
    regex514 => sub { $x =~ s/..(?!\z)\K/ /sgr },
    join     => sub { join(" ", $x =~ /..?/sg) },
    });

似乎使用 unpack() 是最快的

             Rate     join    regex regex514   unpack
join     221828/s       --     -18%     -26%     -42%
regex    271665/s      22%       --     -10%     -29%
regex514 300933/s      36%      11%       --     -22%
unpack   383877/s      73%      41%      28%       --
于 2013-01-29T22:09:21.757 回答
3

尝试这个:

$number = '600000';
$number =~ s/(\d{2})(?!$)/$1 /g;
print $number;

(\d{2})意思是“两个数字”。(?!$)表示“只要字符串的结尾不是紧随其后”,因为数字后面不需要空格。

于 2013-01-29T19:36:29.487 回答
2

这是另一种选择:

use strict;
use warnings;

my $number = 600000;
my $spacedNum = join ' ', $number =~ /..?/g;
print $spacedNum;

输出:

60 00 00
于 2013-01-29T20:19:45.613 回答