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
.
To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.
Ruby | String count() Method count is a String class method in Ruby. In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated.
To find all the matching strings, use String's scan method.
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With