1

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.

Jephron
  • 2,652
  • 1
  • 23
  • 34

2 Answers2

2

You just need the flag /g so JavaScript Regex var re = /\$(.*):([^$]*)/g;

Regex101

\$(.*):([^$]*)

Regular expression visualization

Debuggex Demo

abc123
  • 17,855
  • 7
  • 52
  • 82
  • Matching with `/\$(.*):([^$]*)/g` yields an array with only two values, `['$Label1: Text1 \n Text1 possibly continues ', '$Label2: Text2 $Label3: Text3 Text3 possibly continues' ]`. Does this mean my original regex was wrong? – Jephron Dec 30 '14 at 19:52
  • @Jephron no your regex is correct, just need to loop over matches. – abc123 Dec 30 '14 at 20:19
1

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.

Community
  • 1
  • 1
surui
  • 1,522
  • 12
  • 17