正则表达式在空格之前插入逗号

时间:2011-06-10 12:54:33

标签: javascript jquery ruby regex

如何在空格之前插入N个逗号到此字符串,但不能在句点或其他逗号之后插入?使用ruby或javascript。

2 个答案:

答案 0 :(得分:5)

一个选项:

>>> 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."

答案 1 :(得分:1)

@ jensgram答案的Ruby变体:

str.gsub(/([^,.]) /, $1 + ', ')