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

后端 未结 4 417
清酒与你
清酒与你 2021-01-16 14:50

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

相关标签:
4条回答
  • 2021-01-16 15:26

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

    print 'word word,word,word,'.gsub(/,(?![ ])/, ', ')
    
    0 讨论(0)
  • 2021-01-16 15:37

    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, "
    
    0 讨论(0)
  • 2021-01-16 15:41

    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"
    
    0 讨论(0)
  • 2021-01-16 15:44

    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,"
    
    0 讨论(0)
提交回复
热议问题