[英]Repeating a regex pattern multiple times
使用JavaScript正则表达式。
我正在尝试匹配以下形式的文本块:
$Label1: Text1
Text1 possibly continues
$Label2: Text2
$Label3: Text3
Text3 possibly continues
我想分别捕获标签和文本,以便最终得到
["Label1", "Text1 \n Text1 possibly continues",
"Label2", "Text2",
"Label3", "Text3 \n Text3 possibly continues"]
我有一个正则表达式\\$(.*):([^$]*)
匹配模式的单个实例。
我想也许是这样的: (?:\\$(.*):([^$]*))*
会给我想要的结果,但是到目前为止,我还无法弄清楚有效的正则表达式。
您可以使用以下功能:
function extractInfo(str) {
var myRegex = /\$(.*):([^$]*)/gm;
var match = myRegex.exec(str);
while (match != null) {
var key = match[1];
var value = match[2];
console.log(key,":", value);
match = myRegex.exec(str);
}}
用你的例子,
var textualInfo = "$Label1: Text1\n Text1 possibly continues \n$Label2: Text2\n$Label3: Text3 \n Text3 possibly continues";
extractInfo(textualInfo);
结果:
[Log] Label1 : Text1
Text1 possibly continues
[Log] Label2 : Text2
[Log] Label3 : Text3
Text3 possibly continues
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.