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:
开发者_如何学C["'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?
Lazy should fix this:
/'.*?'/
Another possibility is to use this:
/'[^']*'/
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.
精彩评论