[英]Delete from string first occurrence of given character
string =
"
[title]
{snippet}
[something else in bracket]
{something else}
more text
#tags
"
I want to delete first occurrence of [] and {} 我想删除第一次出现的[]和{}
s.clean_method or regexp should return string like that s.clean_method或regexp应该返回这样的字符串
"
title
snippet
[something else in bracket]
{something else}
more text
#tags
"
Language Ruby 1.9.2 语言Ruby 1.9.2
You need String#sub
(not gsub): 您需要String#sub
(不是gsub):
irb> "[asd]{asd}[asd]{asd}".sub(/\[(.+?)\]/,'\1').sub(/\{(.+?)\}/,'\1')
=> "asdasd[asd]{asd}"
More of the same: 更多相同:
s = "[asd]{asd}[asd]{asd}"
%w({ } [ ]).each{|char| s.sub!(char,'')}
#=> "asdasd[asd]{asd}"
Well, if that's all you want to do, all you need to do is 好吧,如果这就是您想要做的,那么您要做的就是
result = string.sub('{', '').sub('[', '').sub('}', '').sub(']', '')
Of course, that's a terribly inelegant solution, and doesn't consider things like unmatched brackets, etc. 当然,这是一个非常糟糕的解决方案,并且不会考虑括号不匹配等问题。
A better solution would probably be: 更好的解决方案可能是:
pattern1 = /\{(.*?)\}/
pattern2 = /\[(.*?)\]/
match1 = pattern1.match(string)
result = string.sub(match1[0], match1[1])
match2 = pattern2.match(result)
result = result.sub(match2[0], match2[1])
This could probably be simplified, but that's what comes off the top of my head :) 这可能可以简化,但这就是我的脑袋:)
BTW, if you want to replace all instances, all you need to do is use gsub
instead of sub
顺便说一句,如果要替换所有实例,您要做的就是使用gsub
而不是sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.