API呼び出しのrequest-urlを準備するために、RegExを使用して文字列の値をオブジェクトの値で置き換えています。 'テンプレート文字列' のNode.jsの正規表現ですべての一致が表示されない
例:
'https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json'
:OWNERID:CollectionTypeはと:
{ collectionType: 'activities',
date: '2016-10-12',
ownerId: 'xxxxx',
ownerType: 'user',
subscriptionId: 'xxx' }
正規表現:日付が次のオブジェクトからの値に置き換えられます私は以下を使用しています:
/:([\w]+)/gi
これは私がfのあらゆるマッチでグループの内容を使用することを可能にしますオブジェクトから値をエッチします。 (無しマッチ「:」この場合)Iは、要求URLを返すために、次の機能を有する:(URLは「テンプレート文字列」であり、復号は、上記の目的である)
function regexifyUrlTemplate(url, regex, decoded) {
console.log('Regexify URL: ', url)
console.log('Regexify Data: ', decoded)
var m
while ((m = regex.exec(url)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++
}
console.log('Matches: ', m)
url = String(url).replace(m[0], decoded[m[1]])
console.log('Replaced ' + m[0] + ' with ' + decoded[m[1]])
}
console.log('Regexify :', url)
return url
}
コンソールショー私は以下のログを返します:
Regexify URL: https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json
Regexify Data: { collectionType: 'activities',
date: '2016-10-12',
ownerId: 'xxx',
ownerType: 'user',
subscriptionId: 'xxx' }
Matches: [ ':ownerId',
'ownerId',
index: 31,
input: '\'https://api.fitbit.com/1/user/:ownerId/:collectionType/date/:date.json\'' ]
Replaced :ownerId with xxx
Matches: [ ':date',
'date',
index: 59,
input: '\'https://api.fitbit.com/1/user/xxx/:collectionType/date/:date.json\'' ]
Replaced :date with 2016-10-12
Regexify : 'https://api.fitbit.com/1/user/xxx/:collectionType/date/2016-10-12.json'
これは、ownerIdと:dateを置き換えますが、置き換えられません:collectionType。 RegExをregex101.comに確認し、ログから更新された文字列を使って正規表現を調べました。
誰でも理由を説明できますか:collectionTypeが一致していませんか?私が見つけることができる唯一の違いは「T」ですが、問題はないはずです。 ([a-zA-Z]も試しました)。
だったが、言及を忘れてしまった、のために複数のurl-テンプレートがあります異なるAPIコール。 RegExは正常でなければなりません。そうしないと、regex101はすべてのグループを返しません。 – martwetzels
なぜそれはとても複雑になりますか?ちょうど 'url.replace(regex、function(_、k){return decoded [k];})'を実行してください! – Bergi