Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 基于文件夹的正则表达式url重写_Regex - Fatal编程技术网

Regex 基于文件夹的正则表达式url重写

Regex 基于文件夹的正则表达式url重写,regex,Regex,我需要能够获取/calendar/MyCalendar.ics,其中MyCalendar.ics可以是关于ics扩展的任何内容,并将其重写为/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

我需要能够获取/calendar/MyCalendar.ics,其中MyCalendar.ics可以是关于ics扩展的任何内容,并将其重写为/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>
总体思路:

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

路径分隔符是否总是前斜杠

Regex在这方面似乎有些过分;我能想到的最简单的事情就是获取最后一个路径分隔符的索引并进行简单的字符串操作(示例程序的第二部分)

库通常有解析路径的例程。例如,在Java中,我会特别关注Java.io.File对象 getName() 返回由表示的文件或目录的名称 这个抽象路径名。这只是我的姓
路径名的名称序列

正则表达式用于搜索/匹配文本。通常,您将使用正则表达式来定义您在某个文本处理工具中搜索的内容,然后使用特定于工具的方式告诉该工具替换文本的内容

正则表达式语法使用圆括号在整个搜索模式中定义捕获组。许多搜索和替换工具使用捕获组来定义要替换的匹配部分。
我们可以以Java模式和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)); 
}
这将找到请求的模式,但将只使用第一个正则表达式组来创建新字符串

以下是(imho)一个非常好的正则表达式信息站点中正则表达式替换信息的链接:

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)); 
}