简体   繁体   English

匹配多行正则表达式Javascript

[英]Match Multiple Line Regex Javascript

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. 在整个夜晚的大部分时间里,我都把头撞在墙上,所以我期待Stackoverflow众神对此提供帮助。 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: 但是,当我尝试在程序甚至jsfiddle中使用它时,会返回null:

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

Any thoughts? 有什么想法吗?

You probably want to use JavaScript's String.prototype.match with 您可能想将JavaScript的 String.prototype.match
/(?:Name.+)(?:\\n.*){2}/g . /(?: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. 编辑只是看着您的小提琴,它不起作用的原因是因为您忘记添加新行。 ie

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: 我不是JS专家,但是经过一些工作后,我可以提供以下脚本:

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. 这似乎在JSFiddle中工作。 Here i supposed '{' does not lie in between the string you can change this delimiter. 在这里,我认为'{'不在您可以更改此定界符的字符串之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM