oldhomemovie
oldhomemovie

Reputation: 15139

How do I parse a quoted string inside another string?

I want to extract the quoted substrings from inside a string. This is an example:

string = 'aaaa' + string_var_x + 'bbbb' + string_var_y

The output after parsing should be:

["'aaaa'", "'bbbb'"]

The initial solution was to string.scan /'\w'/ which is almost ok.

Still I can't get it working on more complex string, as it's implied that inside '...' there can be any kind of characters (including numbers, and !@#$%^&*() whatever).

Any ideas?

I wonder if there's some way to make /'.*'/ working, but make it less greedy?

Upvotes: 0

Views: 415

Answers (2)

jwueller
jwueller

Reputation: 31006

Lazy should fix this:

/'.*?'/

Another possibility is to use this:

/'[^']*'/

Upvotes: 5

the Tin Man
the Tin Man

Reputation: 160631

An alternate way to do it is:

>> %{string = 'aaaa' + string_var_x + 'bbbb' + string_var_y}.scan(/'[^'].+?'/)  
#=> ["'aaaa'", "'bbbb'"]

String.scan gets overlooked a lot.

Upvotes: 0

Related Questions