取消正则expression式匹配,如果超时

如果需要10秒以上的时间才能取消regex.match操作吗?

我正在使用一个巨大的正则expression式匹配一个特定的文本,有时可能工作,有时可能会失败…

正则expression式: 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秒。 可能吗? 我没有发现任何相关的软件

谢谢。

你可以派生一个subprocess,执行正则expression式匹配,如果它在10秒内没有完成,就把它closures。 可能有点矫枉过正,但它应该工作。

叉可能是你应该使用的,如果你走下这条路。

如果你会原谅我的非纯函数,这段代码将展示你如何在分叉的subprocess和你的主进程之间来回沟通的要点:

index.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'); 

正则expression式,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); 

不过,这可能最终掩盖了真正的问题。 你可能要考虑重新修改你的正则expression式,就像其他海报所build议的那样。