大家好,这是我下面的身体。基本上每个块都由一条没有任何东西的线分隔。每个块都有一个括号中的标题,然后可以有左边的单词格式的任意数量的属性,然后等于,然后是右边的单词。
[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场比赛。每个应该看起来像:[整个匹配,标题,prop1,val1,propN,valN]
匹配1:
['[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)
}
但这是吐出来的:[整场比赛,冠军,预言,valLAST]; 如果我将正则表达式中的最后一个+更改为+?然后它给了 [全场比赛,冠军,道具,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]+))?
我粘贴的数量
请帮助
答案 0 :(得分:0)
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.
希望有所帮助!