Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby regex and grouping

Tags:

regex

ruby

I've got following text 'some-text-here' and try to get the 'text' word from it using groups.

If I use that expression /some-(\w+)-here/ all works fine, but if I try to apply grouping to it /some-(?<group_name>\w+)-here/ it's raise an error Undefined (?...) sequence.

What's I doing wrong?

(Ruby 1.9.2)

Upd: shame on me. It's all from my innatention. Yes, I've use RVM and my ruby version turned on 1.9.2. But I've tested that expression at http://rubular.com/ where it is written at the footer Rubular runs on Ruby 1.8.7. Ruby 1.8.7 and Ruby 1.9.2 have a different regular expression engine. So my expression works on 1.9.2, but does not on 1.8.7

like image 665
ck3g Avatar asked Sep 01 '11 20:09

ck3g


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 is regex Ruby?

Ruby regular expressions (ruby regex for short) help you find specific patterns inside strings, with the intent of extracting data for further processing. Two common use cases for regular expressions include validation & parsing.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.

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.


1 Answers

For me that looks like you are looking at the wrong Ruby. Do you maybe have RVM installed?

1.9.2

>> RUBY_VERSION 
=> "1.9.2"
>> s='some-text-here' 
=> "some-text-here"
>> /some-(?<group_name>\w+)-here/ =~ s 
=> 0
>> group_name #=> "text"

1.8.7

>> RUBY_VERSION
=> "1.8.7"
>> s='some-text-here'
=> "some-text-here"
>> /some-(?<group_name>\w+)-here/ =~ s
SyntaxError: compile error
(irb):2: undefined (?...) sequence: /some-(?<group_name>\w+)-here/
    from (irb):2
like image 174
Michael Kohl Avatar answered Oct 04 '22 22:10

Michael Kohl