Match Multiple Line Regex Javascript

蹲街弑〆低调 提交于 2019-12-04 15:37:26

You probably want to use JavaScript's String.prototype.match with
/(?:Name.+)(?:\n.*){2}/g. The non-capture groups are so you don't double up your results.

var s = '\
Name: John Doe\n\
Address: 123 W Main Street\n\
City: Denver\n\
\n\
\n\
Name: Julie Smith\n\
Address: 1313 Mockingbird Lane\n\
City: Burbank\
';

var arr = s.match(/(?:Name.+)(?:\n.*){2}/g);
/* gives
["Name: John Doe\n\
Address: 123 W Main Street\n\
City: Denver", "Name: Julie Smith\n\
Address: 1313 Mockingbird Lane\n\
City: Burbank"]
*/
// so if you want no new lines,
arr.map(function (e) {return e.replace(/\n/g, ' ');});

Edit Just looked at your fiddle, the reason it doesn't work is because you forgot to put in new lines. i.e.

s = 'a\
b'; // s === "ab"

s = 'a\n\
b'; // s === "a\nb"

I am not a JS expert but after a bit of work around i can offer this script:

var rawdata='\
\
\
Name: John Doe\
Address: 123 W Main Street\
City: Denver\
\
\
Name: Julie Smith\
Address: 1313 Mockingbird Lane\
City: Burbank';

var looppattern = /Name: /g;
var loopnum = rawdata.match(looppattern);

var pattern = /\s{2}([\w\:\s]+)/;
var nummessages = rawdata.replace(new RegExp("Name:", 'g'),"{Name:").split("{");

alert(nummessages[1]);
alert(nummessages[2]);

which seems to work in JSFiddle. Here i supposed '{' does not lie in between the string you can change this delimiter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!