34

Given something like:

 message.split(/\n.* at.* XXXXXXXX wrote:.*/m).first

This works if there is a match, but when there isn't, it just returns all of message.

2 Answers 2

63

If you're trying to count the number of matches, then you're using the wrong method. split is designed to take a string and chop it into bits, but as you've observed, if there aren't any matches, then it returns the whole thing. I think you want to use String.scan instead:

message.scan(/\n.* at.* XXXXXXXX wrote:.*/m).size
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but where does that get the length? IE if any matches were found. I just need to know if a match was found or not.
You should be able to set a regexp like that (works for me). Sorry, just to check, are you saying you literally just want to know if it matches? (i.e. you're not interested in extracting any of the text?)
Ahh, sorry, just realised that you're trying to count how many matches you get, not really trying to split the string at all. Editing answer.
1

Well split will return an array. So you could just check for length > 1

m =  message.split(/\n.* at.* XXXXXXXX wrote:.*/m)
if m.length > 1 
   return m.first
else
   return nil 
end

6 Comments

@Doon, sorry just tried it out... it always returns m.first. Ideas?
Here's what I have: m = to.split(/@mysite.com.*/) if m.length > 1 return m.first.strip else return nil end
Looks like all m.length is doing is counting characters?
in your example what is in to?
What exactly are you trying to do? It looks like you are reading the info in a to field, and trying to get some info there might be better way to get that info.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.