我有以下網址:
localhost:3000/filter/shoes/color/white
我需要將所有斜杠替換-為localhost:3000/.
最終 URL 必須是:
localhost:3000/filter-shoes-color-white
我用 ruby?? 嘗試了一些正則運算式,但沒有任何成功。謝謝。
uj5u.com熱心網友回復:
這是一個匹配所有/但第一個的正則運算式:
\G(?:\A[^\/]*\/)? [^\/]*\K\/
所以你可以這樣做:
"localhost:3000/filter/shoes/color/white".gsub(/\G(?:\A[^\/]*\/)? [^\/]*\K\//,'-')
#=> "localhost:3000/filter-shoes-color-white"
但是如果你的 URI 有一個方案,它就行不通了。
uj5u.com熱心網友回復:
您可以匹配正則運算式
r = /\G\A[^\/]*\/[^\/]*\K\/|\//
str = "localhost:3000/filter/shoes/color/white"
str.gsub(r, '-')
#=> "localhost:3000/filter-shoes-color-white"
Rubular 演示/ PCRE 演示
我已經在 regex101.com 上提供了 PCRE 演示的鏈接,因為它給出了與 Ruby 的正則運算式引擎 (Onigmo) 相同的結果,但它顯示——通過將游標懸停在正則運算式上——每個元素的功能表達。
我們可以以自由間距模式撰寫運算式以使其自檔案化:
/
\G # assert position at the end of the previous match or, if the
# first match, the start of the string
\A # match the beginning of the string
[^\/]* # match zero or more chars other than '/'
\/ # match '/'
[^\/]* # match zero or more chars other than '/'
\K # reset the start of the match to the current position and discard
# all previously-consumed characters from the reported match
\/ # match '/'
| # or
\/ # match '/'
/x # free-spacing regex definition mode
這是反轉字串的第二種方法,進行替換然后反轉結果字串。
r = /\/(?=.*\/)/
str.reverse.gsub(r,'-').reverse
#=> "localhost:3000/filter-shoes-color-white"
這是有效的,因為雖然 Ruby 不支持可變長度的lookbehinds,但它確實支持可變長度的lookaheads。
uj5u.com熱心網友回復:
特爾;博士:
正則運算式是:
\/(?<!localhost:3000\/)
更長的
中國有句古話:授之以漁不如授之以漁。
- 對于正則運算式,您可以使用在線正則運算式站點(例如 regex101.com)立即使用您的正則運算式和測驗字串進行測驗。關聯
- 從 stackoverflow 中找到其他答案,使用其他關鍵字來描述您的情況:Regex for matching something if it is not preceded by else
- 讓你擁有魔法。
uj5u.com熱心網友回復:
這是一個非常簡單的決議問題,所以我質疑是否需要正則運算式。我認為如果你只是用這樣的回圈遍歷字串的字符,代碼可能會更容易理解和維護:
def transform(url)
url = url.dup
slash_count = 0
(0...url.size).each do |i|
if url[i] == '/'
slash_count = 1
url[i] = '-' if slash_count >= 2
end
end
url
end
下面是使用 Ruby 的String#gsub方法更簡單的事情:
def transform2(url)
slash_count = 0
url.gsub('/') do
slash_count = 1
slash_count >= 2 ? '-' : '/'
end
end
uj5u.com熱心網友回復:
使用 Ruby >= 2.7 和 String#partition
如果您沒有將 'https://' 之類的 URI 方案作為字串的一部分傳遞,您可以使用String#partition和String#tr作為單個方法鏈來執行此操作。使用 Ruby 3.0.2
'localhost:3000/filter-shoes-color-white'.partition(?/).
map { _1.match?(/^\/$/) ? _1 : _1.tr(?/, ?-) }.join
#=> "localhost:3000/filter-shoes-color-white"
這基本上依賴于這樣一個事實,即#partition 回傳的第一個陣列元素中沒有正斜杠,而第二個元素包含一個斜杠,僅此而已。然后,您可以自由地使用 #tr 在最后一個元素中用破折號替換正斜杠。
如果您有一個較舊的 Ruby,您將需要一個不同的解決方案,因為 String#partition 在 Ruby 2.6.1 之前沒有被引入。如果您不喜歡使用字符字面量、三元運算子或編號塊引數(在 Ruby 2.7 中引入),那么您可以重構解決方案以適應您自己的風格品味。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/330600.html
標籤:红宝石
