简体   繁体   English

我如何使用正则表达式gsub这个字符串?

[英]How do I gsub this string using regex?

Ok this is rather embarrassing but I have this string: 好的,这很尴尬,但是我有以下字符串:

>> t1
=> ["name: Big Lebowski\n"]

Then I want to replace the entire line with "" 然后我要用""替换整行

>> t2 = t1.collect{|n| n.gsub("/^name.*$/", "")}
=> ["name: Big Lebowski\n"]

I get the same thing. 我也一样 What gives? 是什么赋予了?

You have put your regular expression inside a string, which obviously won't work. 您已将正则表达式放在字符串中,这显然不起作用。

>> t2 = t1.collect{|n| n.gsub(/^name.*$/, "")}
=> ["\n"]

If you also want to get rid of the newline, use the m regex modifier. 如果您还想摆脱换行符,请使用m regex修饰符。

>> t2 = t1.collect{|n| n.gsub(/^name.*$/m, "")}
=> [""]

That's because you're using "gsub" in you block instead of "gsub!" 那是因为您在代码块中使用的是“ gsub”,而不是“ gsub!”。 - as the last one modifies the target. -最后一个修改目标。 Try: 尝试:

t2 = t1.collect{|n| n.gsub!("/^name.*$/", "")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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