使用正则表达式将换行符替换为单词?

时间:2015-03-28 09:36:51

标签: regex

我使用正则表达式将换行替换为单词? itry这个正则表达式代码但没有工作(.*+)/g这是我的正则表达式https://regex101.com/r/bW1gN3/2

输入:

one

two



three


four


five

输出:

one
one
two
two
two
two
three
three
three
four
four
four
four
five

2 个答案:

答案 0 :(得分:1)

我担心一个正则表达式无法做到这一点。你可以使用while循环:

var str = "one\n\ntwo\n\n\n\nthree\n\n\nfour\n\n\nfive\n";
var regex = /(.+)(\n+)/gi;
var str2 = "";

while (result = regex.exec(str))
    str2 += result[2].replace(/\n/g, result[1] + "\n");

答案 1 :(得分:0)

GREP本身不能这样做,但由于你使用的不是纯粹的GREP而是实际的编程语言,你可以使用replace

str = "one\n\ntwo\n\n\n\nthree\n\n\nfour\n\n\nfive";
str = str.replace (/(.+)\n+/g, function (a,b) { return a.replace(/.*\n/g, b+'\n'); } );