Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first match of Ruby regex

Tags:

string

regex

ruby

I'm looking for a way to perform a regex match on a string in Ruby and have it short-circuit on the first match.

The string I'm processing is long and from what it looks like the standard way (match method) would process the whole thing, collect each match, and return a MatchData object containing all matches.

match = string.match(/regex/)[0].to_s 
like image 588
Daniel Beardsley Avatar asked Feb 06 '09 08:02

Daniel Beardsley


People also ask

What does match return in Ruby?

Ruby | Regexp match() function Return: regular expression with the string after matching it.

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.

What does match return in regex?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

What is Rubular?

Rubular is a Ruby-based regular expression editor. It's a handy way to test regular expressions as you write them. To start, enter a regular expression and a test string.


2 Answers

You could try String#[] (as in variableName[/regular expression/]).

This is an example output from IRB:

names = "erik kalle johan anders erik kalle johan anders" # => "erik kalle johan anders erik kalle johan anders" names[/kalle/] # => "kalle" 
like image 88
Presidenten Avatar answered Sep 21 '22 18:09

Presidenten


You can use []: (which is like match)

"[email protected]"[/\+([^@]+)/, 1] # matches capture group 1, i.e. what is inside () # => "account2" "[email protected]"[/\+([^@]+)/]    # matches capture group 0, i.e. the whole match # => "+account2" 
like image 42
Benjamin Crouzier Avatar answered Sep 18 '22 18:09

Benjamin Crouzier