在每个单词之前用大写字母放置逗号和空格

Led*_*Led 2 ruby regex

我正在使用ruby,我试图在每个单词之前放置一个逗号和一个空格,除了开头的单词之外还有一个大写字母.

str = Taxonomy term Another term One more

puts str.gsub(/\s/, ', ')
Run Code Online (Sandbox Code Playgroud)

输出> Taxonomy, term, Another, term, One, more

期望的输出> Taxonomy term, Another term, One more

我的正则表达式技能非常生疏,所以我只是停留在这个阶段.

知道如何达到我想要的输出吗?

Syo*_*yon 5

您可以捕获大写字母并在替换中使用它.

str.gsub(/\s(\p{lu})/, ', \1')
Run Code Online (Sandbox Code Playgroud)

使用\p{lu}将匹配任何Unicode大写字母.

puts "Taxonomy term Another term ?ne ?ess".gsub(/\s(\p{lu})/, ', \1');

Output:
Taxonomy term, Another term, ?ne ?ess
Run Code Online (Sandbox Code Playgroud)