使用正则表达式将位置与可选的子位置匹配

时间:2012-08-21 00:23:19

标签: regex url

我想将/spam/(.*)重定向到/$1(包括/spam//)和/spam/,但不是{{1}转到/spam(.*)$1

因此/$1变为/spam/eggs/bacon/eggs/bacon/spam/都变为/spam/不会变为spameggs/bacon

正则表达式eggs/bacon(chars)对完成了什么?

3 个答案:

答案 0 :(得分:1)

非常简单:^.*((?<=^/spam/).*|(?<=^/spam))$/$1

Testhttp://ideone.com/YqAAA):

'/spam'          --> '/'
'/spam/'         --> '/'
'/spam/one'      --> '/one'
'/spam/one/two'  --> '/one/two'

答案 1 :(得分:1)

我不确定RegExp的味道,但我会尝试类似......

/(spam($|/))?(.*) ==&gt; /$3

这是一个PHP示例。

$rx = '~/(spam($|/))?(.*)~';
$arr = array(
    '/spam',
    '/spam/',
    '/spam/eggs/bacon',
    'spameggs/bacon',
    '/spameggs/bacon'
);
foreach ($arr as $val) {
    echo "<b>Before:</b> $val\n<b>After:</b> " . preg_replace($rx,'/$3',$val) . PHP_EOL.PHP_EOL;
}

输出

  

之前: /垃圾邮件
  之后: /

     

之前: / spam /
  之后: /

     

之前: / spam / eggs / bacon
  之后: / eggs / bacon

     

之前: spameggs / bacon
  之后: spameggs / bacon

     

之前: / spameggs / bacon
  之后: / spameggs / bacon

答案 2 :(得分:0)

模式:/spam(?:/(.*)|()$)

替换:/$1

这将正确替换,是迄今为止发布的最简单的解决方案,并且如果路径不是您正在考虑的形式(即如果它不匹配{{1 }或/spam