尝试在JavaScript正则表达式中重复捕获块

Trying to repeat capture block in JavaScript regex

本文关键字:JavaScript 正则表达式      更新时间:2023-09-26

下面是我的body。基本上,每个块都由一行隔开,上面什么都没有。每个块在括号中有一个标题,然后可以有任意数量的属性,格式为word在左边,然后等号,然后words在右边。

[General]
StartWithLastProfile=0
[Profile0]
Name=default
IsRelative=1
Path=Profiles/vr10qb8s.default
Default=1
[Profile1]
Name=cleanER One Here
IsRelative=1
Path=Profiles/k46wtieb.cleanER One Here

我想要得到3个匹配。每个应该看起来像:[whole match,title,prop1,val1,propN,valN]

Match1:

['[General]
StartWithLastProfile=0','General','StartWithLastProfile','0']

Match2:

['[Profile0]
Name=default
IsRelative=1
Path=Profiles/vr10qb8s.default
Default=1','Profile0','Name','default','IsRelative','1','Path','Profiles/vr10qb8s.default','Default','1']

等等

这是我的正则表达式:
       var patt = /'[.*'](?:'s+?(['S]+)=(['S]+)+/mg;
       var blocks = [];
       var match;
       while (match = patt.exec(readStr)) {
        console.log(match)
       }

但这是吐出来的:[whole match, title, propLAST, valLAST];。如果我把正则表达式的最后一个+改成+?然后得到[whole match, title, propFIRST, valFIRST];

这个正则表达式工作,但有一个噱头:

var patt = /'[.*'](?:'s+?(['S]+)=(['S]+))(?:'s+?(['S]+)=(['S]+))?(?:'s+?(['S]+)=(['S]+))?(?:'s+?(['S]+)=(['S]+))?(?:'s+?(['S]+)=(['S]+))?/mg;

现在返回:

[ "[General]
StartWithLastProfile=0", "StartWithLastProfile", "0", undefined, undefined, undefined, undefined, undefined, undefined, undefined, 1 more… ]
[ "[Profile0]
Name=default
IsRelative=1
Path=Profiles/vr10qb8s.default
Default=1", "Name", "default", "IsRelative", "1", "Path", "Profiles/vr10qb8s.default", "Default", "1", undefined, 1 more… ]
[ "[Profile1]
Name=cleanER
IsRelative=1
Path=Profiles/k46wtieb.clean", "Name", "cleanER", "IsRelative", "1", "Path", "Profiles/k46wtieb.clean", undefined, undefined, undefined, 1 more… ]

我不希望那些不必要的未定义在最后,这个模式是有限的多少(?:'s+?(['S]+)=(['S]+))?我粘贴在模式的末尾

LIVE DEMO

JavaScript代码

string = string.split(/'n'n/g); // split along the double newline to get blocks
var matches = [];  // the complete matches array has `match1`, `match2`, etc.
string.forEach(function(elem, index){ // for each block
  var matchArr = [];               // make a matchArr
  matchArr.push(elem); // wholeMatch 
  elem.replace(/'[([a-z0-9]+)']/i, function(match, $1){    
    matchArr.push($1); // get the title  
  });
  elem.replace(/([a-z]+)=(.+)/ig, function(match, $1, $2){
    matchArr.push($1); // property
    matchArr.push($2); // value
  });
  matches.push(matchArr);  // push the `match` in bigger `matches` array
});
console.log(matches); // get the whole matches array
// You can use `matches[0]` to get the 1st match, and so on.

希望有帮助!