Match Multiple Line Regex Javascript

孤街浪徒 提交于 2019-12-09 23:01:14

问题


I have beat my head against the wall for the better part of the night so I am looking to the stackoverflow Gods to help with this. I have a text string that I am attempting to parse into an array. See the example below:

Name: John Doe
Address: 123 W Main Street
City: Denver


Name: Julie Smith
Address: 1313 Mockingbird Lane
City: Burbank

What I would like to get is an array that looks like this:

[Name: John Doe Address: 123 W Main Street City: Denver, Name: Julie Smith Address 1313 Mockingbird Lane City: Burbank]

I started with the following regex and it works fine in regexpal:

(Name.+)(\n.*){2}

However, when I try to use that in my program or even jsfiddle, I get a null return:

http://jsfiddle.net/auqHA/1/

Any thoughts?


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/16918599/match-multiple-line-regex-javascript

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