Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails, ruby - Given a Regex - Determine the Match Count

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.

like image 347
AnApprentice Avatar asked Nov 18 '10 19:11

AnApprentice


People also ask

Can you count with regex?

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.

How do you count the number of strings in Ruby?

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.

What method should you use when you want to get all sequences matching a regex pattern in a string?

To find all the matching strings, use String's scan method.

What does =~ mean in Ruby regex?

=~ 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.


2 Answers

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 
like image 88
Paul Russell Avatar answered Sep 23 '22 06:09

Paul Russell


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 
like image 32
Doon Avatar answered Sep 24 '22 06:09

Doon