2012-04-22 59 views
3

考虑到这些网址:正则表达式URL重写,如果与其他然后

1: http://site/page-name-one-123/ 
2: http://site/page-name-set2/ 
3: http://site/set20 

我写这个表达式将被应用到最后的URL段

(?(?<=set[\d])([\d]+)|([^/]+)) 

我会想什么do只是在URL段以'set'开头并且紧跟在后面的数字时捕获'set'后面的每个数字;否则我想使用整个段(不包括斜杠)。

正如我写这个正则表达式,它匹配任何不是'/'的字符。我想我在测试陈述中做错了什么。 任何人都可以指出我的权利?

感谢

UPDATE 感谢Josh输入我打得四处了一下,发现这一个更符合我的需求:

set-(?P<number>[0-9]+)|(?P<segment>[^/]+) 

回答

1

我希望这种模式可以帮助你,我根据您的要求把它放在一起。您可能想要设置一些组以避免捕获,以便只获取所需的细分。但是,它确实捕获了您的集合 URL的没有集合在开始。

((?<=/{1})(((?<!set)[\w|-]*?)(\d+(?=/?))|((?:set)\d+))) 

我建议使用RegExr来挑选它,如果你需要的话。

+0

这正是我一直在寻找...谢谢! – brainondev 2012-04-22 12:33:12

0

试试这个:

((?<=/)set\d+|(?<=/)[^/]+?set\d+)

说明

<!-- 
Options:^and $ match at line breaks 

Match the regular expression below and capture its match into backreference number 1 «((?<=/)set\d+|(?<=/)[^/]+?set\d+)» 
    Match either the regular expression below (attempting the next alternative only if this one fails) «(?<=/)set\d+» 
     Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=/)» 
     Match the character “/” literally «/» 
     Match the characters “set” literally «set» 
     Match a single digit 0..9 «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
    Or match regular expression number 2 below (the entire group fails if this one fails to match) «(?<=/)[^/]+?set\d+» 
     Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=/)» 
     Match the character “/” literally «/» 
     Match any character that is NOT a “/” «[^/]+?» 
     Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?» 
     Match the characters “set” literally «set» 
     Match a single digit 0..9 «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
-->