Replace character between slashes
http://photos-c.ak.fbcdn.net/hphotos-ak-as开发者_如何学编程h4/####_####_####_###_####_a.jpg http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/wefawf/vawvaw/a####_####_####_###_####.jpg
I'm trying to create a Regex that replaces the 'a' in between the last '/' and '.jpg' with an 'n'.
I'm completely lost right now. I'm using Perl and from what I understand it should be along these lines:
s/^.*\/.*$/n/g
... except I'm not sure where to put the 'a'.
If there's guaranteed only one 'a', then Paul's answer will suffice, with a couple of small changes:
$foo =~ s|a([^/]*\.jpg)\Z|n$1|;
First, I have no '/' preceding the 'a'. It's sufficient to specify that there are no '/'s between 'a' and '.jpg', and that allows for both of your examples (with the '/' present it only matched the second of your examples). I also removed the '/g' modifier and added '\Z' to anchor the regex to the end of the string. We only need the last match.
If there may be multiple 'a's between the final '/' and '.jpg', things get only slightly trickier:
while ($foo =~ s|(/[^/]*)a([^/]*\.jpg\Z)|$1n$2|) { }
Basically, while there are still 'a's between the final '/' and '.jpg', keep swapping 'a's for 'n's one at a time.
$foo =~ s?/a([^/]*.jpg)?/n$1?g;
This replaces the first 'a' between the last '/' and '.jpg' with an 'n' (tested):
$ cat test.pl
#!/usr/bin/env perl
use strict;
use warnings;
sub a_with_n {
shift;
s!(.*/.*)a(.*\.jpg)!$1n$2!;
return $_;
}
my @test_strings = (
'http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/####_####_####_###_####_a.jpg',
'http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/wefawf/vawvaw/a####_####_####_###_####.jpg'
);
foreach (@test_strings) {
printf("%s\n", a_with_n($_));
}
$ ./test.pl
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/####_####_####_###_####_n.jpg
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/wefawf/vawvaw/n####_####_####_###_####.jpg
Another way of doing this replacement (matching multiple occurrences of "a"):
use strict;
use warnings;
while (<DATA>) {
my $last = rindex ($_, "/"); # get index of last "/"
substr ($_,$last) =~ s/a/n/g; # change all "a" to "n" starting from last "/"
print;
}
__DATA__
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/####_####_####_###_###a#_aa.jpg
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/wefawf/vawvaw/a####_####_####_###_####.jpg
Output:
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/####_####_####_###_###n#_nn.jpg
http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/wefawf/vawvaw/n####_####_####_###_####.jpg
精彩评论