views:

68

answers:

3

Hi,

I have string "(1,2,3,4,5,6),(1,2,3)" I would like to change it to "('1','2','3','4','5','6'),('1','2','3')" - replase all parts that mathces /([^,)("])/ with the '$1', '$2' etc

+1  A: 
"(1,2,3,4,5,6),(1,2,3)".gsub(/([^,)("]\w*)/,"'\\1'")

gsub is a "global replace" method in String class. It finds all occurrences of given regular expression and replaces them with the string given as the second parameter (as opposed to sub which replaces first occurrence only). That string can contain references to groups marked with () in the regexp. First group is \1, second is \2, and so on.

Matt
This will work, but you need to add a '+' after the set to get strings, floats, etc. Things might also get tricky with whitespace.
Brian Clements
I made a mistake in regexp it should be ([^,)("]\w*) for more complicate strings. thanks for the answer, could you explain it , please
Bohdan Pohorilets
I added an explanation and changed the regexp
Matt
I should read documentation more carefully
Bohdan Pohorilets
@Bohdan Pohorilets Wait, does this pick up "3.3" as an entire "3.3" and not "3" and ".3"? When I test it, it also breaks up strings with spaces and tabs.
Keng
+1  A: 

Try

mystring.gsub(/([\w.]+)/, '\'\1\'')

This will replace numbers (ints/floats) and words with their "quote-surrounded" selves while leaving punctuation (except the dot) alone.

Tim Pietzcker
Yes, it also works
Bohdan Pohorilets
A: 

UPDATED: I think you want to search for this

(([^,)("])+)

And replace it with this

'$1'

the looks for anything 1 or more times and assigns it to the $1 variable slot due to using the parenthesis around the "\d". The replace part will use what it finds as the replacement value.

Keng