简体   繁体   中英

How can I update parts of the string that matches some regexp

我有字符串"(1,2,3,4,5,6),(1,2,3)"我想将其更改为"('1','2','3','4','5','6'),('1','2','3')" - 用'$1', '$2'替换所有数学/([^,)("])/ '$1', '$2'等等

"(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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM