Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do named capture in ruby

Tags:

regex

ruby

I want to name the capture of string that I get from scan. How to do it?

"555-333-7777".scan(/(\d{3})-(\d{3})-(\d{4})/).flatten #=> ["555", "333", "7777"] 

Is it possible to turn it into like this

{:area => "555", :city => "333", :local => "7777" } 

or

[["555","area"], [...]] 

I tried

"555-333-7777".scan(/((?<area>)\d{3})-(\d{3})-(\d{4})/).flatten 

but it returns

[] 
like image 837
RubyNoobie Avatar asked Sep 16 '13 10:09

RubyNoobie


People also ask

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

What does this regex do?

Short for regular expression, a regex is a string of text that lets you create patterns that help match, locate, and manage text. Perl is a great example of a programming language that utilizes regular expressions. However, its only one of the many places you can find regular expressions.

What is non capturing group in regex?

Non-capturing groups are important constructs within Java Regular Expressions. They create a sub-pattern that functions as a single unit but does not save the matched character sequence. In this tutorial, we'll explore how to use non-capturing groups in Java Regular Expressions.

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.


1 Answers

You should use match with named captures, not scan

m = "555-333-7777".match(/(?<area>\d{3})-(?<city>\d{3})-(?<number>\d{4})/) m # => #<MatchData "555-333-7777" area:"555" city:"333" number:"7777"> m[:area] # => "555" m[:city] # => "333" 

If you want an actual hash, you can use something like this:

m.names.zip(m.captures).to_h # => {"area"=>"555", "city"=>"333", "number"=>"7777"} 

Or this (ruby 2.4 or later)

m.named_captures # => {"area"=>"555", "city"=>"333", "number"=>"7777"} 
like image 130
Sergio Tulentsev Avatar answered Oct 06 '22 00:10

Sergio Tulentsev