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

编程入门 行业动态 更新时间:2024-10-03 10:42:11

如果超<a href=https://www.elefans.com/category/jswz/34/1624762.html style=时则取消正则表达式匹配"/>

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

如果需要超过 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+

工作示例:

所以..如果超过 10 秒我想取消操作。是否可以?我在 sof

中找不到任何相关内容

谢谢。

回答如下:

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

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

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

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

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);

不过,这可能最终掩盖了真正的问题。您可能需要考虑像其他海报所建议的那样重新设计您的正则表达式。

更多推荐

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

本文发布于:2024-05-30 13:46:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时则   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!