简体   繁体   English

删除rails字符串中以>开头的行

[英]Removing lines that begin with > in a rails string

I'm trying to remove any lines that begin with the character '>' in a long string (ie replies to an email). 我正在尝试删除任何以长字符串中的字符“>”开头的行(即回复电子邮件)。

In PHP I'd iterate over each line with an if statement, in linux I'd try and use sed or awk. 在PHP中,我用if语句迭代每一行,在linux中我尝试使用sed或awk。

What's the most elegant rails approach? 什么是最优雅的导轨方法?

你可以试试这个:

your_string.gsub(/^\>.+\n/,'')

它应该按预期工作:

your_string.lines.to_a.reject{|line| line[0] == '>'}.join

Your question is implying that the input is one string, containing multiple lines. 您的问题是暗示输入是一个字符串,包含多行。 Do you want the output to be just one string with multiple lines as well? 您是否希望输出只是一个包含多行的字符串? I'm assuming yes. 我假设是的。

either using String and Array operations: 使用String和Array操作:

str.lines.reject{|x| x =~ /^>/}.join   # this will return a new string, without those ">" lines

or using Regular Expressions: 或使用正则表达式:

str.gsub(/^>.+\n*/. '')

Better Solution: 改善方案:

You will need to use non-greedy multi-line matching mode for your Regular Expression: 您需要为正则表达式使用非贪婪的多行匹配模式:

str.gsub(/^>.*?$\n*/m, '')   # by using gsub!() you can modify the string in place

^> matches your ">" character at the start of a line ^>在行的开头匹配您的“>”字符

.*?$ matches any characters after the start character until the end of the line (non-greedy) 。*?$匹配起始字符后的任何字符,直到行结束(非贪婪)

\\n* matches the newline character itself if any (you want to remove that as well) \\ n *匹配换行符本身(如果有的话)(你也想删除它)

the "m" at the end of the regular expressions indicates multi-line matching , which will apply the RegExp for each line in the string. 正则表达式末尾的“m”表示多行匹配,它将对字符串中的每一行应用RegExp。

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

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