Reputation: 2748
Using JavaScript regexes.
I'm trying to match blocks of text in the form:
$Label1: Text1
Text1 possibly continues
$Label2: Text2
$Label3: Text3
Text3 possibly continues
I want to capture the label and the text separately, so that I'll end up with
["Label1", "Text1 \n Text1 possibly continues",
"Label2", "Text2",
"Label3", "Text3 \n Text3 possibly continues"]
I've got a regex \$(.*):([^$]*)
which matches a single instance of the pattern.
I thought maybe something like this: (?:\$(.*):([^$]*))*
would give me the desired results, but so far I haven't been able to figure out a regex that works.
Upvotes: 1
Views: 1436
Reputation: 1542
you can use the following function:
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);
}}
Using your example,
var textualInfo = "$Label1: Text1\n Text1 possibly continues \n$Label2: Text2\n$Label3: Text3 \n Text3 possibly continues";
extractInfo(textualInfo);
The results:
[Log] Label1 : Text1
Text1 possibly continues
[Log] Label2 : Text2
[Log] Label3 : Text3
Text3 possibly continues
there's a good answer to this question that explains it all.
Upvotes: 1