【发布时间】:2011-03-31 14:13:49
【问题描述】:
假设我有一个字符串:Hey what's up @dude, @how's it going?
我想删除所有@how's之前的字符。
【问题讨论】:
假设我有一个字符串:Hey what's up @dude, @how's it going?
我想删除所有@how's之前的字符。
【问题讨论】:
或使用正则表达式:
str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"
您可以在here 阅读有关环视的信息
【讨论】:
sub! 可以使用时,不需要gsub!,对吧?另请注意(根据我的回答),您需要 \A 锚和/或 m 标志,以防字符串在要匹配的文本之前有换行符。
s = "Hey what's up @dude, @how's it going?"
s.slice(s.index("@how")..-1)
# => "@how's it going?"
【讨论】:
0..s.index("@how")吗?
index 将返回nil。因此,他应该在执行slice 之前检查nil,或者计划挽救因将nil 的索引传递给slice 而产生的错误。
实际上有数十种方法可以做到这一点。以下是我会使用的:
如果您想保留原始字符串:
str = "Hey what's up @dude, @how's it going?"
str2 = str[/@how's.+/mi]
p str, str2
#=> "Hey what's up @dude, @how's it going?"
#=> "@how's it going?"
如果你想改变原始字符串:
str = "Hey what's up @dude, @how's it going?"
str[/\A.+?(?=@how's)/mi] = ''
p str
#=> "@how's it going?"
...或...
str = "Hey what's up @dude, @how's it going?"
str.sub! /\A.+?(?=@how's)/mi, ''
p str
#=> "@how's it going?"
您需要\A 锚定在字符串的开头,并使用m 标志来确保您匹配多行。
也许最简单的方法是改变原始版本:
str = "Hey what's up @dude, @how's it going?"
str.replace str[/@how's.+/mi]
p str
#=> "@how's it going?"
【讨论】:
String#slice 和 String#index 工作正常,但如果针不在大海捞针中,则会出现 ArgumentError: bad value for range。
在这种情况下使用String#partition 或String#rpartition 可能会更好:
s.partition "@how's"
# => ["Hey what's up @dude, ", "@how's", " it going?"]
s.partition "not there"
# => ["Hey what's up @dude, @how's it going?", "", ""]
s.rpartition "not there"
# => ["", "", "Hey what's up @dude, @how's it going?"]
【讨论】:
一种只获取您感兴趣的部分的简单方法。
>> s="Hey what's up @dude, @how's it going?"
=> "Hey what's up @dude, @how's it going?"
>> s[/@how.*$/i]
=> "@how's it going?"
如果您确实需要更改字符串对象,您可以随时使用s=s[...]。
【讨论】:
>> "Hey what's up @dude, @how's it going?".partition("@how's")[-2..-1].join
=> "@how's it going?"
不区分大小写
>> "Hey what's up @dude, @HoW's it going?".partition(/@how's/i)[-2..-1].join
=> "@HoW's it going?"
或使用scan()
>> "Hey what's up @dude, @HoW's it going?".scan(/@how's.*/i)[0]
=> "@HoW's it going?"
【讨论】:
m 标志来匹配后面可能出现的任何换行符。
您也可以直接在字符串上调用[](与slice相同)
s = "Hey what's up @dude, @how's it going?"
start_index = s.downcase.index("@how")
start_index ? s[start_index..-1] : ""
【讨论】: