English 中文(简体)
Regex autoincrement replacements
原标题:

is there a string in regular expressions that can instruct it to autoincrement it s replacements, whether they be numbers or letters.

Thank you

for instance, I have strings that should be number 1, 2, 3, 4, 5 but they are currently numbered as 1, 1, 1, 1, 1

how would I replace the number in those 5 individual similar strings to be 1, 2, 3, 4, 5

最佳回答

I m not familiar with the syntax of TextWrangler; however, it uses pcre so this should be what you want as long as you have a way to assign an initial value to your incrementing variable (in this case, I use $ii)... the script below replaces any occurrence of "pizza-x" with "pizza-0", "pizza-1"...

@foo = ( pizza ,  pizza-a ,  pizza-b ,  pizza-c );
$ii = 0;
foreach (@foo) {
    $_ =~ s/(pizza-)[a-z]/"$1".$ii++/e;
    print "$_
";
}

Results...

[mpenning@mpenning-t60 Desktop]$ perl foo.pl 
pizza
pizza-0
pizza-1
pizza-2

The magic comes from s///e; and $ii++; be sure you enclose the non-incrementing string in quotes and concatenate with a period.

Alternatively, just do your auto-increment mangling with perl -pi -e $ii = 0; s/something/"here".$ii++/e ` directly on the text file (make a backup copy first, of course).

问题回答

暂无回答




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签