简体   繁体   中英

Repeating a regex pattern multiple times

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.

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

Regex101

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

正则表达式可视化

Debuggex Demo

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM