Add space after commas only if it doesn't already?

泪湿孤枕 提交于 2020-01-11 07:11:41

问题


Is there a way to add a space after commas in a string only if it doesn't exist.

Example:

word word,word,word,

Would end up as

word word, word, word,

Is there a function in ruby or rails to do this?

This will be used on hundreds of thousands of sentences, so it needs to be fast (performance would matter).


回答1:


Using negative lookahead to check no space after comma, then replace with comma and space.

print 'word word,word,word,'.gsub(/,(?![ ])/, ', ')



回答2:


Just use a regular expression to replace all instances of "," not followed by a space with ", ".

str = "word word,word,word,"

str = str.gsub(/,([^ ])/, ', \1') # "word word, word, word,"



回答3:


If the string contains no multiple adjacent spaces (or should not contain such), you don't need a regex:

"word word, word, word,".gsub(',', ', ').squeeze(' ')
  #=> "word word, word, word, "



回答4:


Add missing space:

 "word word,word,word,".gsub(/,(?=\w)/, ', ') # "word word, word, word,"

and removing the last unnecessary comma if necessary

"word word,word,word,".gsub(/,(?=\w)/, ', ').sub(/,\Z/, '') # "word word, word, word"


来源:https://stackoverflow.com/questions/22947779/add-space-after-commas-only-if-it-doesnt-already

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