0
如何在空格前插入N個逗號到這個字符串中,而不是在句號或其他逗號後面插入?使用紅寶石或JavaScript。正則表達式在空格前插入逗號
如何在空格前插入N個逗號到這個字符串中,而不是在句號或其他逗號後面插入?使用紅寶石或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."
紅寶石變化:
str.gsub(/([^,.]) /, $1 + ', ')
難道這被重新用於在整個字符串中只插入3個(例如)? – ahabman 2011-06-10 13:33:57
@ahabman嗯,我想你可以添加一個隨機元素:'str.replace(/([,。])?/ g,function($ 0,$ 1){return $ 1 || Math.random()> .2? $ 0:',';});'只會替換合格空格的〜1/5('.2')。如果你願意,你可以*記錄最大數量的空白(例如3)。 – jensgram 2011-06-14 05:32:49