給定一個url,以下正則表達式可以在URL中的某些點處插入/替換單詞。Perl正則表達式在特定位置插入/替換字符串
代碼:
#!/usr/bin/perl
use strict;
use warnings;
#use diagnostics;
my @insert_words = qw/HELLO GOODBYE/;
my $word = 0;
my $match;
while (<DATA>) {
chomp;
foreach my $word (@insert_words)
{
my $repeat = 1;
while ((my $match=$_) =~ s|(?<![/])(?:[/](?![/])[^/]*){$repeat}[^/]*\K|$word|)
{
print "$match\n";
$repeat++;
}
print "\n";
}
}
__DATA__
http://www.stackoverflow.com/dog/cat/rabbit/
http://www.superuser.co.uk/dog/cat/rabbit/hamster/
10.15.16.17/dog/cat/rabbit/
(在__DATA__
與HELLO
單詞的第一個例子URL)給出的輸出:
http://www.stackoverflow.com/dogHELLO/cat/rabbit/
http://www.stackoverflow.com/dog/catHELLO/rabbit/
http://www.stackoverflow.com/dog/cat/rabbitHELLO/
http://www.stackoverflow.com/dog/cat/rabbit/HELLO
在哪裏,我現在堅持:
我現在想改變正則表達式錫安使輸出將是什麼樣子如下圖所示:
http://www.stackoverflow.com/dogHELLO/cat/rabbit/
http://www.stackoverflow.com/dog/catHELLO/rabbit/
http://www.stackoverflow.com/dog/cat/rabbitHELLO/
http://www.stackoverflow.com/dog/cat/rabbit/HELLO
#above is what it already does at the moment
#below is what i also want it to be able to do as well
http://www.stackoverflow.com/HELLOdog/cat/rabbit/ #<-puts the word at the start of the string
http://www.stackoverflow.com/dog/HELLOcat/rabbit/
http://www.stackoverflow.com/dog/cat/HELLOrabbit/
http://www.stackoverflow.com/dog/cat/rabbit/HELLO
http://www.stackoverflow.com/HELLO/cat/rabbit/ #<- now also replaces the string with the word
http://www.stackoverflow.com/dog/HELLO/rabbit/
http://www.stackoverflow.com/dog/cat/HELLO/
http://www.stackoverflow.com/dog/cat/rabbit/HELLO
但我無法得到它的一個正則表達式中自動執行此操作。
這件事的任何幫助,將不勝感激,非常感謝
你的意思是把'/ dog/cat/ra bbit/HELLO'兩次? – ikegami 2013-03-01 16:34:41
@ikegami - 很好的問題,我希望它不會重複,我把它留在問題中,讓其他人可以理解我想要更容易實現的輸出類型,謝謝 – 2013-03-01 16:40:02
**這可能不是正則表達式的工作,而是使用您選擇語言的現有工具。**您使用的是哪種語言?您可能不想使用正則表達式,而是使用已編寫,測試和調試的現有模塊。 如果您使用PHP,您需要['parse_url'](http://php.net/manual/en/function.parse-url.php)函數。 如果您使用Perl,您需要['URI'](http://search.cpan.org/dist/URI/)模塊。 如果您使用的是Ruby,請使用['URI'](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html)模塊。 – 2013-03-01 17:27:49