Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp in ruby - can I use parenthesis without grouping?

Tags:

regex

ruby

I have a regexp of the form:

/(something complex and boring)?(something complex and interesting)/

I'm interested in the contents of the second parenthesis; the first ones are there only to ensure a correct match (since the boring part might or might not be present but if it is, I'll match it by accident with the regexp for the interesting part).

So I can access the second match using $2. However, for uniformity with other regexps I'm using I want that somehow $1 will contain the contents of the second parethesis. Is it possible?

like image 914
Gadi A Avatar asked May 13 '11 13:05

Gadi A


2 Answers

Use a non-capturing group:

r = /(?:ab)?(cd)/
like image 169
Frank Schmitt Avatar answered Sep 26 '22 04:09

Frank Schmitt


This is a non-ruby regexp feature. Use /(?:something complex and boring)?(something complex and interesting)/ (note the ?:) to achieve this.

By the way, in Ruby 1.9, you can do /(something complex and boring)?(?<interesting>something complex and interesting)/ and access the group with $~[:interesting] ;)

like image 42
J-_-L Avatar answered Sep 25 '22 04:09

J-_-L