0

I want the following spaces within the quotes to be stripped out, but only the spaces that are contiguous before and after a quote within matching quotes.

this is " a " quoted "string " with " lots" of "edge " cases " that " need spaces removed. It \" also \" has "escaped" quotes just to really annoy you!

It should look like...

this is "a" quoted "string" with "lots" of "edge" cases "that" need spaces removed. It \"also\" has "escaped" quotes just to really annoy you!

I's this even possible in a single regex? If not then any solution will do.

4

3 回答 3

1

这是一个很烦人的,呵呵

str = %Q{this is " a " quoted "string " with " lots" of "edge " cases " that " need spaces removed. It \\" also \\" has "escaped" quotes just to really annoy you!}

str.gsub! /(\\?"|)((?:.(?!\1))+.)(?:\1)/ do |match|
  match.gsub(/^(\\?")\s+|\s+(\\?")$/, "\\1\\2").strip
end

尽管如此...

this is "a" quoted "string" with "lots" of "edge" cases "that" need spaces removed. It \"also\" has "escaped" quotes just to really annoy you!

正则表达式可视化

正则表达式


这很烦人的原因是因为str.gsub!产生一个字符串到块而不是MatchDatastr.match这样。那好吧...

于 2013-11-08T01:18:49.063 回答
0
str.gsub /(\\?")\s*([^"\s]+)\s*(\\?")/, '\1\2\3'
于 2013-11-08T09:00:18.570 回答
0

我可能会遗漏一些东西,因为我觉得这更容易一些:

str.gsub(/("|\\").*?\1/){|x| x.delete(' ')}

但是,我将删除引号之间的所有空格。这更正确但有点难看:

str.gsub(/("|\\")(.*?)("|\\")/){$1+$2.strip+$3}
于 2013-11-08T08:19:07.187 回答