我正在尝试配置正则表达式模式,以便在第二个正斜杠后面的字符串末尾添加#
,如下所示:
/leisure/venuename/news
=> /leisure/venuename#/news
/leisure/venuename/page/384
=> /leisure/venuename#/page/384
以下代码
gsub(/^(.*)(\/.*)$/, '\1#\2')
对于第一个模式按预期工作,但对于第二个模式,它提供了:
/leisure/venuename/page#/384
有没有办法用一种模式捕获两个组?
答案 0 :(得分:2)
不要使用.*
来匹配正斜杠,而是更明确一点:
^(\/[^\/]+\/[^\/]+)(\/.*)$
<强>可视化:强>
<强>解释强>
^ # 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
答案 1 :(得分:0)
你做错了两件事。
gsub
。\2
。这样做:
"/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"
它简单,干净且非常易读,这在代码即将推出一段时间时非常重要。