简体   繁体   中英

Replace ruby string with gsub with conditions for multiple strings

I have as string as "pas" and "with_pas". I want to replace it with blank string. Now I am doing as follows

string.gsub("pas","").gsub("with_pas","") 

In some scenario i get the string as "pas" and in some other with "with_pas".

Is there a better way to do this?

您可以使用当前的方法,但是需要更改顺序,否则将无法按预期工作:

string.gsub("with_pas","").gsub("pas","")

那使用正则表达式呢?

string.gsub(/(with_)?pas/, "")
str.gsub(/pas|with_pas/, '').squeeze

这将删除单词,并且squeeze将删除gsub添加的额外空间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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