5

如何解决 JavaScript 中 RegExp 不幂等的问题?

 3 years ago
source link: https://www.ixiqin.com/2021/07/how-to-solve-the-regexp-in-javascript-not-idempotent-problem/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何解决 JavaScript 中 RegExp 不幂等的问题?

在对 WXMarkdown 进行改造的时候,我准备使用 Vercel 提供的 cloudFunction 来实现。

在执行时,出现了一个奇怪的问题,当我使用 RegExp 进行匹配的时候,会出现匹配成功和匹配失败的情况。

当我回溯代码时,发现问题出现在

import type { NextApiRequest, NextApiResponse } from "next";
const URL = require("url");
const rule = /BV([0-9a-zA-Z]{1,10})/g;
export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<MDResponse>
) {
    const { url } = req.body;
    const result = rule.exec(url);
}

result 的匹配结果不是每次都是可用的,会交替一次 null,一次有结果。

搜索后了解到,这是由于 RegExp 本身是具有状态的,在这种情况下,由于后一次的调用复用了之前的请求,所以出现了一次有结果,一次没有结果。

在这种情况下,有两种解决方案:

  1. 在使用 Rule 之前,对其进行重置状态,即在进行匹配之前,先设定 rule.lastIndex 为 0
  2. 另一种解决方案是将 rule 的定义放置在导出的函数内部,这样就可以在后续执行的过程中,重新初始化。

Reference

https://stackoverflow.com/questions/38910334/regular-expression-exec-function-does-not-work-multiple-times

发布日期:2021年7月3日
分类:Node.js
d9b147a3b7e8d89bf4a5ddd0518bca30?s=85&d=monsterid&r=g

作者:白 宦成

Generalist, contact me at [email protected]

查看白 宦成的所有文章。

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论

显示名称 *

电子邮箱地址 *

网站地址


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK