简体   繁体   English

从 ruby​​ 中的字符串中提取和删除子字符串

[英]extract and remove substring from a string in ruby

I have a string as below我有一个字符串如下

"/br/watch/123456"

I need to remove /br and extract only /watch/123456.我需要删除 /br 并只提取 /watch/123456。 what is the best way to achieve it in ruby.在 ruby​​ 中实现它的最佳方法是什么。

You can use sub to remove first occurrence of /br from string, else gsub to remove all occurrences您可以使用sub从字符串中删除第一次出现的/br ,否则使用gsub删除所有出现的

"/br/watch/123456".sub("/br","")
# => "/watch/123456"

Use sub.使用子。 sub helps to do a single replacement on strings. sub有助于对字符串进行单个替换。 The below code will remove the /br sub-string only if it's present at the start.下面的代码将删除/br子字符串仅当它出现在开始时。

> "/br/watch/123456".sub(/^\/br/, '')
=> "/watch/123456"

If it's always three characters that should be removed you can.如果总是应该删除三个字符,则可以。

"/br/watch/123456"[3..-1]

or more verbose and probably slower或更冗长,可能更慢

"/br/watch/123456".chars.drop(3).join

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM