开发者

How do I parse a quoted string inside another string?

开发者 https://www.devze.com 2023-01-27 00:45 出处:网络
I want to extract the quoted substrings from inside a string. This is an example: string = \'aaaa\' + string_var_x + \'bbbb\' + string_var_y

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消