繁体   English   中英

Javascript:如何从多行字符串中解析出一行?

[英]Javascript: How to parse a line out of a multi-line string?

目前,我有一个使用<pre>显示的大字符串段落,如下所示,其中每一行都使用新行表示:

SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem

由此,我该如何解析build:e9kem 数据每次都不同,因此一旦它识别出单词build ,就只想解析该行。

/^build:(.*)$/m

应该做的伎俩。 m标志将导致^$锚在行的开头和结尾匹配。

如果你称之为

string.match(regexp)

匹配部分(在build: ,匹配.*的部分,即字符串e9kem )将位于结果数组的第二个元素中。

 const regexp = /^build:(.*)$/m; const stringPar = `SchoolDistrictCode:291238-9 location_version:3.4 build:e9kem`; console.log(stringPar.match(regexp)[1]);

当然,如果没有匹配项, match将返回null ,因此您可能需要检查:

var matches = stringPar.match(regexp);
if (matches) console.log(matches[1]);
else console.log("No match.");

或者,另一个常见的习语是

console.log((stringPar.match(regexp) || [])[1]);

如果不匹配,它将记录undefined

暂无
暂无

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

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