[英]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.