说我有以下字符串:
hello/there/
hello/there/friend
我需要一个能产生以下内容的正则表达式:
hello/there
hello/there
到目前为止,我所拥有的是str[/.*[\/]+/]
,但这保留了最后一个斜杠。
答案 0 :(得分:1)
答案 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
答案 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