1
$string = "On 0 8 February 2 0 1 4 , he visited the fair";

I want to replace the spaces between the numbers, so it becomes "On 08 February 2014, he visited the fair"

How can I do this with regex? I can do a for loop index by index, but given large amounts of text, it will be slow.

This is an idea of what I'm trying to achieve:

$string =~ s/([0-9]\s)+/substr($string,$-[0],$+[0]-$-[0])/g;

but it won't work since substr is not treated as a function within the regex. Any ideas?

3 Answers 3

3

You can use look behind, and look ahead to filter such spaces,

$string =~ s/[0-9]\K [ ]+ (?=[,0-9])//xg;
Sign up to request clarification or add additional context in comments.

1 Comment

I did this $string =~ s/[0-9]\K [ ]+ (?=[[:punct:]0-9])//xg;
0

Try this code:

do{
    $string =~s/(\d+)\s+(\d+)/$1$2/g;
} while($string =~/(\d+)\s+(\d+)/);

Comments

0

You can also try the following regex $string =~ s/(?<=\d)\s+(?![a-z])//ig;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.