[英]Javascript: How to parse a line out of a multi-line string?
Currently I have a big string paragraph displayed using <pre>
like the following where each line is represented using new line:目前,我有一个使用<pre>
显示的大字符串段落,如下所示,其中每一行都使用新行表示:
SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem
From this, how can I parse just the build:e9kem
out?由此,我该如何解析build:e9kem
? The data varies every time, so once it recognizes the word build
, would like to parse just that line.数据每次都不同,因此一旦它识别出单词build
,就只想解析该行。
/^build:(.*)$/m
should do the trick.应该做的伎俩。 The m
flag will cause the ^
and $
anchors to match at the beginning and end of the line. m
标志将导致^
和$
锚在行的开头和结尾匹配。
If you call this as如果你称之为
string.match(regexp)
The matching part (after the build:
, the part matching .*
, which is the string e9kem
) will be in the second element of the resulting array.匹配部分(在build:
,匹配.*
的部分,即字符串e9kem
)将位于结果数组的第二个元素中。
const regexp = /^build:(.*)$/m; const stringPar = `SchoolDistrictCode:291238-9 location_version:3.4 build:e9kem`; console.log(stringPar.match(regexp)[1]);
Of course, match
returns null
if there are no matches, so you may want to check that:当然,如果没有匹配项, match
将返回null
,因此您可能需要检查:
var matches = stringPar.match(regexp);
if (matches) console.log(matches[1]);
else console.log("No match.");
Or, another common idiom is或者,另一个常见的习语是
console.log((stringPar.match(regexp) || [])[1]);
which will log undefined
if there is not match.如果不匹配,它将记录undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.