簡體   English   中英

如何更改我的正則表達式以匹配多個承諾語法?

[英]How to change my regex to match more than one promise syntax?

我有匹配承諾代碼語法的正則表達式。

正則表達式也在 promise 語法中匹配(按組名:a、b、c 和 d)。

所以使用正則表達式我知道回調里面有什么以及參數是什么。

then\([\n\s]+function\s*\((?<a>.*)\)\s*\{[\n\s]+(?<b>[\s\S]+)\},[\n\s]*function\s*\((?<c>.*)\)\s*\{[\n\s]*(?<d>[\s\S]+)?\}[\n\s]*\);

正則表達式101

當我只有一種承諾語法時,這很好用: 在此處輸入圖片說明

但是當我有多個承諾短語時就不那么匹配了: 在此處輸入圖片說明

有沒有辦法讓每個短語組成一組並且仍然有內部組?

在 Javascript 代碼中是最重要的。

在控制台中,我記錄了在then之后匹配所有內容的b

代碼和盒子.io

console.clear();

const code = `
promise().then(
  function (result) {
    ...
  },
  function (err) { ... }
);

..............................

promise().then(
  function (result) {
    ...
  },
  function (err) { ... }
);
`;

const p = new RegExp(/then\([\n\s]+function\s*\((?<a>.*)\)\s*\{[\n\s]+(?<b>[\s\S]+)\},[\n\s]*function\s*\((?<c>.*)\)\s*\{[\n\s]*(?<d>[\s\S]+)?\}[\n\s]*\);/gmi);

code.replace(p, (x, a,b,c,d) => {

  console.log({ x, a, b, c });
});

老實說,在使用 JavaScript 的正則表達式時,這是一項令人不快的任務,因為我們錯過了遞歸和其他有用的功能; 我試圖一次性做到這一點( regex101 ),但最后,我認為最好匹配 then(...); 先局部再解剖內部; 例如像這樣:

 const regex = /(then\\()(?:(?!\\1|\\\\).)*?\\);/gs; const rxInner = /(?:function\\s*\\((?<a>.*?)\\)\\s*\\{\\s+(?<b>[\\s\\S]+?)\\},\\s*function\\s*\\((?<c>.*?)\\))/gs; const str = ` promise().then( function (result1) { ... }, function (err) { ... } ); .............................. promise().then( function (result2) { ... }, function (err) { ... } );`; let match = regex.exec(str); do { console.log(match); let m = rxInner.exec(match[0]); do { console.log(` a:${m.groups.a} b:${m.groups.b} c:${m.groups.c}`); } while((m = rxInner.exec(match[0])) !== null); } while((match = regex.exec(str)) !== null);
 <script src="https://unpkg.com/xregexp/xregexp-all.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM