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.

2 Answers 2

2

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

Regex101

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

Regular expression visualization

Debuggex Demo

Sign up to request clarification or add additional context in comments.

2 Comments

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 no your regex is correct, just need to loop over matches.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.