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 occurren开发者_运维技巧ce of [] and {}
s.clean_method or regexp should return string like that
"
title
snippet
[something else in bracket]
{something else}
more text
#tags
"
Language Ruby 1.9.2
You need String#sub
(not 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
精彩评论