Regular Expression to escape double quotes inside single quotes

半腔热情 提交于 2019-12-04 20:08:11

The biggest problem is going to be figuring out where all the strings are, since you can't parse all of JS or PHP with a regex. However, if I assume that you don't care about comments, this Ruby code will catch most cases (but you should review its output):

#!/usr/bin/ruby -p

gsub!(/'((?:[^\\']|\\[\\'])+)'/) do |m|
  %Q{"#{$1.gsub("\\'","'").gsub(/\\[^\\]/) { "\\#{$0}" }.gsub('"','\\"')}"}
end

This code takes whatever's presented on stdin / the contents of the file arguments, finds a single-quoted string (taking into account the possible presence of \\ and \'), and then, for its replacement, runs a series of substitutions within the matched string (sanitizing backslashes, etc.). The result is printed to stdout. If you want a more automated approach, replace the first line with #!/usr/bin/ruby -pi.bak; then, whatever file arguments are presented have the substitution run on them destructively in-place. The old files are kept with an additional .bak extension.

To run this code, if you haven't used Ruby before: save it as anything, such as fix-sq.rb; run chmod +x fix-sq.rb; and then run ./fix-sq.rb file1 file2 file3.

That regex only captures one " because you're only asking for one. If you want to capture all the quotes, you need something more like (".*)+ in the middle. That says, "Capture one or more of this pattern: a double quote followed by zero or more of any characters."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!