我需要能够采取/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