Joseph Le Brech
Joseph Le Brech

Reputation: 6653

Removing lines in a text file based on the beginning characters

I have an email message which looks like this:

Hey how are you?

On Saturday [email protected] wrote:
> something
> On Friday [email protected] wrote:
>> previous thing

How would I remove the lines that start with > as well as lines that include [email protected] wrote

Should I even keep the "someone wrote" part as that could remove legitimate lines, maybe only removing that line if it's the last line.

I'm trying this out:

message_filtered = message_txt.to_s.split("\n").each do |m|
  if m[0] != ">" then
    return m
  end
end

puts message_filtered

I could push m to an array and then join that array with \n but i'm trying a shorter way.

Upvotes: 5

Views: 2805

Answers (4)

Hauleth
Hauleth

Reputation: 23586

Try

message_filtered = message_txt.lines.reject { |line|
  line[0] == '>' || line =~ YOUR_EMAIL_REGEXP
}.join('\n')

To remove lines that start with > you can use:

message_filtered = message_txt.gsub(/(^>.+)/, '') # should work but not tested

Upvotes: 5

the Tin Man
the Tin Man

Reputation: 160571

String.gsub with a simple regex can do this:

text = <<EOT
Hey how are you?

On Saturday [email protected] wrote:
> something
> On Friday [email protected] wrote:
>> previous thing
EOT

puts text.gsub(/(?:^>|On \w+ [email protected] wrote:).+\n/m, '')

# => "Hey how are you?\n\n"

Upvotes: 0

Baldrick
Baldrick

Reputation: 24340

my proposition:

message_filtered = '';
message_txt.to_s.lines {|line| message_filtered << line unless line[0] == '>' }

Upvotes: 2

nkm
nkm

Reputation: 5914

How about this,

> str = "Hey how are you?\nOn Saturday [email protected] wrote:\n> something\n> On Friday [email protected] wrote:\n>> previous thing"
> str.split("\n").reject{|msg| msg =~ /^>/ || msg =~ /@example.com/}.join("\n")
 => "Hey how are you?"

Upvotes: 1

Related Questions