我需要能夠採取/calendar/MyCalendar.ics其中MyCalendar.ics coudl關於ICS擴展的任何東西,並將其重寫到/feeds/ics/ics_classic.asp?MyCalendar。集成電路正則表達式url基於文件夾重寫
感謝
我需要能夠採取/calendar/MyCalendar.ics其中MyCalendar.ics coudl關於ICS擴展的任何東西,並將其重寫到/feeds/ics/ics_classic.asp?MyCalendar。集成電路正則表達式url基於文件夾重寫
感謝
C:\x>perl foo.pl
Before: a=/calendar/MyCalendar.ics
After: a=/feeds/ics/ics_classic.asp?MyCalendar.ics
...or how about this way?
(regex kind of seems like overkill for this problem)
b=/calendar/MyCalendar.ics
index=9
c=MyCalendar.ics (might want to add check for ending with '.ics')
d=/feeds/ics/ics_classic.asp?MyCalendar.ics
下面的代碼:
C:\x>type foo.pl
my $a = "/calendar/MyCalendar.ics";
print "Before: a=$a\n";
my $match = (
$a =~ s|^.*/([^/]+)\.ics$|/feeds/ics/ics_classic.asp?$1.ics|i
);
if(! $match) {
die "Expected path/filename.ics instead of \"$a\"";
}
print "After: a=$a\n";
print "\n";
print "...or how about this way?\n";
print "(regex kind of seems like overkill for this problem)\n";
my $b = "/calendar/MyCalendar.ics";
my $index = rindex($b, "/"); #find last path delim.
my $c = substr($b, $index+1);
print "b=$b\n";
print "index=$index\n";
print "c=$c (might want to add check for ending with '.ics')\n";
my $d = "/feeds/ics/ics_classic.asp?" . $c;
print "d=$d\n";
C:\x>
總體思路:
如果你真的用正則表達式解決這個問題,一個半棘手的問題是確保你的捕獲組(parens)排除路徑分隔符。 有些事情要考慮:
你的路徑分隔符總是正斜槓?
正則表達式似乎對此過度殺傷;我可以想到的最簡單的事情就是獲取最後一個路徑分隔符的索引並執行簡單的字符串操作(示例程序的第二部分)。
庫往往有解析路徑的例程。在Java中,我會查看java.io.File對象,例如,具體爲 getName() 返回此抽象路徑名錶示的文件或目錄的名稱,由 表示。這只是 中的姓氏路徑名的序列號
正則表達式用於搜索/匹配文本。通常,您將使用正則表達式來定義您搜索某個文本操作工具的內容,然後使用特定於工具的方式告訴該工具要替換文本的內容。
正則表達式語法使用圓括號來定義整個搜索模式中的捕獲組。許多搜索和替換工具使用捕獲組來定義要替換哪部分匹配。
我們可以以Java Pattern和Matcher類爲例。爲了與Java匹配器完成你的任務,你可以使用下面的代碼:
Pattern p = Pattern.compile("/calendar/(.*\.(?i)ics)");
Matcher m = p.matcher(url);
String rewritenUrl = "";
if(m.matches()){
rewritenUrl = "/feeds/ics/ics_classic.asp?" + url.substring(m.start(1), m.end(1));
}
這將找到所請求的模式,但只會採取的第一個正則表達式組用於創建新的字符串。
這裏是一個非常好的正則表達式信息站點中的正則表達式替換信息的鏈接:http://www.regular-expressions.info/refreplace.html