配置正则表达式模式以在两个正斜杠后应用

时间:2014-08-11 12:10:38

标签: ruby regex

我正在尝试配置正则表达式模式,以便在第二个正斜杠后面的字符串末尾添加#,如下所示:

  • /leisure/venuename/news => /leisure/venuename#/news
  • /leisure/venuename/page/384 => /leisure/venuename#/page/384

以下代码

gsub(/^(.*)(\/.*)$/, '\1#\2')

对于第一个模式按预期工作,但对于第二个模式,它提供了:

  • /leisure/venuename/page#/384

有没有办法用一种模式捕获两个组?

3 个答案:

答案 0 :(得分:2)

不要使用.*来匹配正斜杠,而是更明确一点:

^(\/[^\/]+\/[^\/]+)(\/.*)$

<强>可视化:

From Debuggex.com

<强>解释

^            # Assert position at the beginning of the line
(            # Begin first capturing group
    \/       #  Match literal '/'
    [^\/]+   #  Match any character that is not a '/', one or more times
    \/       #  Match literal '/'
    [^\/]+   #  Match any character that is not a '/', one or more times
)            # End of first capturing group
(            # Begin second capturing group
    \/       #  Match literal '/'
    .*       #  Match everything else
)            # End of second capturing group
$            # Assert position at the end of the line

RegEx Demo

答案 1 :(得分:0)

你做错了两件事。

  1. 您不应在此使用gsub
  2. 您不应在此使用\2
  3. 这样做:

    "/leisure/venuename/news"
    .sub(%r"((?:/[^/]*){2})", '\1#')
    #=> "/leisure/venuename#/news"
    
    "/leisure/venuename/page/384"
    .sub(%r"((?:/[^/]*){2})", '\1#')
    #=> "/leisure/venuename#/page/384"
    

答案 2 :(得分:0)

虽然可以使用正则表达式执行此操作,但我不确定它是否是更易读/可维护的路由。我这样做:

foo = '/leisure/venuename/news'.split('/')
foo[2] << '#'
foo.join('/') # => "/leisure/venuename#/news"

foo = '/leisure/venuename/page/384'.split('/')
foo[2] << '#'
foo.join('/') # => "/leisure/venuename#/page/384"

它简单,干净且非常易读,这在代码即将推出一段时间时非常重要。