您如何在该字符串中插入N个逗号,而不要在空格前而不是句点或另一个逗号后插入?使用ruby或javascript。

最佳答案

一种选择:

>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus.";
>>> str.replace(/([^,.]) /g, '$1, ');
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus."


另外,您可以采用另一种方式来mimick negative lookbehind

>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus.";
>>> str.replace(/([,.])? /g, function($0, $1) { return $1 ? $0 : ', '; });
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus."

07-28 05:43