A regular expression corresponding to the number of characters whose number has been parsed before

Let's say I have a file containing lines that look like this:

"7sunrIsEfoo"
"10ecological09"
"3bedtime"

Each line begins with digits that represent the number n. I want to combine n characters with them. The output should be:

sunrIsE
ecological
bed

Is there a way to do this using regex? My first attempt:

([0-9]*)[a-zA-Z]{\1}

but it does not work.

+3
source share
4 answers

This is not possible with regex.

([0-9]*) it simply “remembers” the numbers as a substring: they cannot be used numerically.

+4
source

In Ruby, you can use:

result = string[/(\d+)([a-zA-Z]+)/,2][0,$1.to_i]

This will give you the expected result.

+2
source

. . () ,

(?<=1).|(?<=2)..|(?<=3)...| 

etc. (although you are better off using the reverse order, otherwise you will have trouble reaching 11). Please note that you should not use this method if you really have no other way =)

0
source

Here's how to do it in Perl:

#!/usr/local/bin/perl
use strict;
use warnings;

my @list = ("7sunrIsEfoo", "10ecological09", "3bedtime");
foreach(@list) {
    s/^(\d+)(.+)$/substr($2, 0, $1)/e;
    print $_,"\n";
}

output:

sunrIsE
ecological
bed
0
source

All Articles