删除第二个斜杠之后的所有内容

时间:2019-05-28 14:16:17

标签: regex ruby

说我有以下字符串:

hello/there/
hello/there/friend

我需要一个能产生以下内容的正则表达式:

hello/there
hello/there

到目前为止,我所拥有的是str[/.*[\/]+/],但这保留了最后一个斜杠。

3 个答案:

答案 0 :(得分:1)

使用模式^[^\/]+\/[^\/]+

说明:

^-匹配字符串的开头

[^\/]+-匹配/

以外的一个或多个字符

\/-从字面上匹配/

匹配的字符串将是您想要的输出。

Demo

答案 1 :(得分:0)

在这里,如果斜杠的数量是常数,我们很可能会使用此表达式:

count

我们在以下三个组中捕获所需数据:

(.+?)\/(\s.+)(\/.+)

测试

(.+?)  # Upto the first slash
(\s.+) # an space up to the last slash
(\/.+) # last slash and any char after that except for new lines

DEMO

答案 2 :(得分:0)

data

或者,按照惯例:

R = /
    \A   # match beginning of string
    .*?  # match >= 0 characters
    \/   # match '/'
    .*?  # match zero or more characters, lazily
    \K   # forget everything matched so far
    \/   # match '/'
    .*   # match zero or more characters
    \z   # match end of string
    /x   # free-spacing regex definition mode

R = /\A.*?\/.*?\K\/.*\z/ 

def my_chop(str)
  str.sub(R, '')
end

请注意,正则表达式中需要my_chop "hello" #=> "hello" my_chop "hello/" #=> "hello/" my_chop "hello/there" #=> "hello/there" my_chop "hello/there/" #=> "hello/there" my_chop "hello/there/friend" #=> "hello/there" ,因为Ruby不支持可变长度的lookbehinds。正则表达式也可以编写如下:

\K

Ruby确实支持变长预行,所以我们可以这样写:

R = /\A[^\/]*\/[^\/]*\K\/.*\z/

R = /.*\/(?=.*?\/.*\z)/

def my_chop(str)
  str.reverse.sub(R, '').reverse
end