如何使用正则表达式可选择在最后过滤掉一些单词

时间:2016-11-23 23:06:48

标签: regex

我有这样的字符串

/city/town/movie/M-12345
/city/town/movie/M-23456/shown
/city/town/movie/M-34567/coming

如果路径以id结尾

,我希望有一个正则表达式来过滤掉电影ID
(?<path1>.*)(?:(\/M-[0-9]+$))

希望path1成为

/city/town/movie
/city/town/movie/M-23456/shown
/city/town/movie/M-34567/coming

然而实际结果只是

/city/town/movie

知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

使用以下模式:

^.+(?=\/M-\d+$)|^.+(?!\/M-\d+$)

https://regex101.com/r/F76E3f/1

答案 1 :(得分:0)

如果你正在使用PHP

,那就非常简单
<?php
$urls = array('/city/town/movie/M-12345','/city/town/movie/M-23456/shown','/city/town/movie/M-34567/coming');
$regex = '~M-\d+$~';

$cleaned = preg_replace($regex, '', $urls);
print_r($cleaned);

/*
Array
(
    [0] => /city/town/movie/
    [1] => /city/town/movie/M-23456/shown
    [2] => /city/town/movie/M-34567/coming
)
*/    

?>