javascript - 如果超时则取消正则表达式匹配

标签 javascript regex node.js

如果需要超过 10 秒才能完成,是否可以取消 regex.match 操作?

我正在使用一个巨大的正则表达式来匹配特定的文本,有时可能有效,有时可能会失败...

正则表达式:MINISTÉRIO(?:[^P]*(?:P(?!ÁG\s:\s\d+\/\d+)[^P]*)(?:[\s\S]*?))PÁG\s:\s+\d+\/(\d+)\b(?:\D*(?:(?!\1\/\1)\d\D*)*)\1\/\1(?:[^Z]*(?:Z(?!6:\s\d+)[^Z]*)(?:[\s\S]*?))Z6:\s+\d+

工作示例:https://regex101.com/r/kU6rS5/1

所以.. 如果超过 10 秒,我想取消操作。是否可以?我没有在 sof 中找到任何相关内容

谢谢。

最佳答案

您可以生成一个执行正则表达式匹配的子进程,如果它在 10 秒内未完成则将其终止。可能有点矫枉过正,但它应该有效。

fork如果您沿着这条路走下去,这可能是您应该使用的。

如果你能原谅我的非纯函数,这段代码将演示如何在 fork 的子进程和你的主进程之间来回通信的要点:

索引.js

const { fork } = require('child_process');
const processPath = __dirname + '/regex-process.js';
const regexProcess = fork(processPath);
let received = null;

regexProcess.on('message', function(data) {
  console.log('received message from child:', data);
  clearTimeout(timeout);
  received = data;
  regexProcess.kill(); // or however you want to end it. just as an example.
  // you have access to the regex data here.
  // send to a callback, or resolve a promise with the value,
  // so the original calling code can access it as well.
});

const timeoutInMs = 10000;
let timeout = setTimeout(() => {
  if (!received) {
    console.error('regexProcess is still running!');
    regexProcess.kill(); // or however you want to shut it down.
  }
}, timeoutInMs);

regexProcess.send('message to match against');

regex-process.js

function respond(data) {
  process.send(data);
}

function handleMessage(data) {
  console.log('handing message:', data);
  // run your regex calculations in here
  // then respond with the data when it's done.

  // the following is just to emulate
  // a synchronous computational delay
  for (let i = 0; i < 500000000; i++) {
    // spin!
  }
  respond('return regex process data in here');
}

process.on('message', handleMessage);

不过,这可能最终掩盖了真正的问题。您可能需要像其他发帖人建议的那样考虑修改您的正则表达式。

关于javascript - 如果超时则取消正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859506/

相关文章:

javascript - 想要将变量传递给 Node 异步的 map 方法

javascript - 如何? PHP 从 &lt;script&gt; 中回显数据

javascript - javascript/jquery 文件是否有多重包含保护?

javascript - 避免跨域检查和其他浏览器安全检查

正则表达式匹配特定范围内的2位数字

javascript - react native : Why does a valid Javascript regex pattern not work on Android?

Javascript 替换 : don't split word on hyphen (regular expressions)

javascript - 类型错误 : Cannot set property 'user' of undefined at

node.js - 解码特殊西里尔字母

javascript - 我可以检测浏览器的书签工具栏是否启用了 JavaScript 吗?