Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 多次重复正则表达式模式_Javascript_Regex - Fatal编程技术网

Javascript 多次重复正则表达式模式

Javascript 多次重复正则表达式模式,javascript,regex,Javascript,Regex,使用JavaScript正则表达式 我正在尝试匹配表单中的文本块: $Label1: Text1 Text1 possibly continues $Label2: Text2 $Label3: Text3 Text3 possibly continues 我想分别捕获标签和文本,这样我将以 ["Label1", "Text1 \n Text1 possibly continues", "Label2", "Text2", "Label3", "Text3 \n

使用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"]
我有一个regex
\$(.*):([^$]*)
,它匹配该模式的一个实例


我想可能是这样的:
(?:\$(.*)([^$]*)*
会给我想要的结果,但到目前为止,我还没有找到一个有效的正则表达式。

你只需要标记
/g
所以JavaScript正则表达式
var re=/\$(.*)([^$]*)/g


您可以使用以下功能:

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

有一个很好的答案可以解释这一切。

匹配
/\$(.*)([^$]*)/g
生成一个只有两个值的数组,
['$Label1:Text1\n Text1可能继续','$Label2:Text2$Label3:Text3可能继续']
。这是否意味着我原来的正则表达式是错误的?@Jephron不,你的正则表达式是正确的,只需要循环匹配。
[Log] Label1 :  Text1
    Text1 possibly continues 

[Log] Label2 :  Text2

[Log] Label3 :  Text3 
     Text3 possibly continues