0

我需要能够获取 /calendar/MyCalendar.ics ,其中 MyCalendar.ics 可以是任何具有 ICS 扩展的内容,并将其重写为 /feeds/ics/ics_classic.asp?MyCalendar.ics

谢谢

4

2 回答 2

0
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>

一般想法:

如果您确实使用正则表达式解决了这个问题,那么需要确保您的捕获组(括号)排除路径分隔符。需要考虑的一些事项:

您的路径分隔符总是正斜杠吗?

正则表达式似乎对此有点过分了;我能想到的最简单的方法是获取最后一个路径分隔符的索引并进行简单的字符串操作(示例程序的第二部分)。

库通常具有解析路径的例程。例如,在 Java 中,我会查看 java.io.File 对象,特别是 getName() 返回此抽象路径名表示的文件或目录的名称。这只是路径名的名称序列中的最后一个名称

于 2012-07-19T17:37:41.900 回答
0

正则表达式用于搜索/匹配文本。通常你会使用正则表达式来定义你搜索的一些文本操作工具,然后使用工具特定的方式来告诉工具用什么来替换文本。

正则表达式语法使用圆括号来定义整个搜索模式中的捕获组。许多搜索和替换工具使用捕获组来定义要替换的匹配部分。
我们可以以 Java Pattern 和 Matcher 类为例。要使用 Java Matcher 完成任务,您可以使用以下代码:

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

于 2012-07-19T17:38:32.253 回答