简体   繁体   English

从字符串中删除首次出现的给定字符

[英]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.

相关问题 删除字符串中的第一个“#”字符 - Rails - Delete the first “#” character in a String - Rails 从第二次出现的字符中拆分字符串 - Split string from the second occurrence of the character 通过首先出现一个非字母字符来中断字符串? - Break a string by first occurrence of a non-letter character? gsub-大写首次出现的字符转换 - gsub - transform in uppercase first occurrence of a character 如何从字符串的开头到在Ruby中的字符串中的特定索引之前的字符的最后一次出现取子字符串 - How to take a substring from the beginning of a string up to the last occurrence of a character that is before a specific index in the string in Ruby 如何找到给定字符串中最后一次出现的子字符串? - How to find last occurrence of a substring in a given string? 每次出现特定字符时都会拆分一个字符串吗? - Split a string at every occurrence of particular character? 如何从字符串末尾的最后一个字符删除到字符串中间的斜线? - how to delete from the last character at the end of a string, to a slash in the middle of a string? Ruby - 用另一个字符串替换第一次出现的子字符串 - Ruby - replace the first occurrence of a substring with another string Ruby 匹配 gsub 替换的第一次出现的字符串 - Ruby match first occurrence of string for a gsub replacement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM