9

RegExp /g 踩坑

 3 years ago
source link: https://paugram.com/coding/regexp-g-debug.html/comment-page-1
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

RegExp /g 踩坑

2021.04.15进击的码农 4 361

不是所有的正则都需要在末尾加上 /g 的,因为这会导致出现一些你难以想象的问题...

我做了一个上传组件,并在今天将其从 React 版本迁移成原生 JS 版。在测试的时候输入了很多 console.log 用于 Debug,结果发现了奇怪的一幕,注释掉 console.log 前后的代码执行结果竟然是不一致的!见了鬼了!

// props.allowed 的值是 /jpeg|png|gif|pdf/g
// 正则匹配
if(props.allowed && props.allowed instanceof RegExp){
  console.log("reg", props.allowed.test(files[0].type));

  if(props.allowed.test(files[0].type)){
    console.log("success");
    failed("filetype1", files[0].type);
    return;
  }
  else{
    console.log("wrong")
  }
}

具体表现就是,上传的文件类型(files[0].type)是 png,然而却没有输出「success」,而是「wrong」。但如果把 console.log("reg", props.allowed.test(files[0].type)); 这行注释掉,就会恢复正常。

难不成 .test 是异步的?上下文执行返回的结果不一样?在控制台运行,test 的执行是「几乎」同步的,不然肯定返回 Promise 了...

为什么说是「几乎」呢?因为在某些特殊情况(DOM 操作)下,执行是存在较大延迟的。例如你前面刚刚创建一个元素,就打算去尝试删除它...

我把这个奇怪的问题告诉了 @Innei,他说这个之前也踩过坑,其实是 /g 的情况下,返回的是一个迭代器,每次运行的结果是不一样的。

例如下面的代码,第一次执行是 true,第二次返回的就是 false 了。用 execmatch 就看的更明显。

字符串有一个符合条件的结果,是这样的:

let reg = /beauty/g;

reg.test("Dear my beauty")
// true

reg.test("Dear my beauty")
// false

reg.test("Dear my beauty")
// true

reg.test("Dear my beauty")
// false

字符串有多个符合条件的结果,是这样的;

let reg = /beauty/g;

reg.test("Dear my beauty, and beauty")
// true

reg.test("Dear my beauty, and beauty")
// true

reg.test("Dear my beauty, and beauty")
// false

可以看出来,这里确实是迭代器,每次执行会按照匹配结果的顺序来,直到匹配结束返回 false

去掉正则里面的 /g 就可以了。只需要检测「是否包含符合条件的值」的情况下(匹配一个结果),则无需使用 /g

什么时候才适合使用 /g 呢?需要内容进行批量替换的时候。

"beauty & beauty".replace(/beauty/g, "cute")
// "cute & cute"

"beauty & beauty".replaceAll(/beauty/g, "cute")
// "cute & cute"

"beauty & beauty".replace(/beauty/, "cute")
// "cute & beauty"

"beauty & beauty".replaceAll(/beauty/, "cute")
// 报错 non-global RegExp argument
Paul

特立独行的一只前端狗。本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!如本站内容对你有所帮助的话,不妨 捐助支持 一下?同时欢迎关注 我的日记,唠嗑(分享)每日的折腾经历。

已有 4 条评论

g?b=qq&nk=945879305&s=100
路过的甲同学 3 天前

本来只是路过瞅瞅,兄弟你学校就我家门口是真的有缘,左边海莲山庄,右边四中是吧(网上冲浪还是隐晦点)。俺也是搞前端的,有兴趣可以认识下😂

夏目贵志

越来越强了~~

Paul

@夏目贵志 徒弟都超过我了,强者太多了...

夏目贵志

@Paul 这点真不能否认,我现在看很多博客都是初中生一个比一个猛。
佩服!!你继续加油哈!!


Recommend

  • 27
    • www.tuicool.com 5 years ago
    • Cache

    Hello... RegExp?!

    In this post, I'll try to explain the basics of regular expressions . Keep in mind that this sort-of tutorial is aimed for those who would like to learn regexps a bit better and/or are just starting a...

  • 9
    • yourbasic.org 3 years ago
    • Cache

    Regexp tutorial and cheat sheet

    Regexp tutorial and cheat sheet yourbasic.org/golang A regular expression is a sequence of characters that define a search pattern.

  • 19

    REGEXP_LIKE – Happy thoughts whilst searching for multiple substrings in Oracle SQL Posted on

  • 11

    A quiz about RegExp.prototype.exec return values and numeric indexes (or indices or however you people pluralize that word).A quiz about RegExp.prototype.exec return values and numeric indexes (or indices or however you people pluralize that...

  • 5
    • studygolang.com 3 years ago
    • Cache

    regexp 正则包

    regexp 正则包 直立猿 · 大约2小时之前 · 12 次点击 · 预计阅读时间 5 分钟 · 不到1分钟之前 开始浏览     ...

  • 9

    前端有的时候需要对 url 或者 http 请求进行处理,比如有的 api 不需要带 token 访问,有的直接请求第三方接口。之前处理的方式是简单的包含判断,后来发现这样不够严谨也容易出问题。正确的做法是用正则去匹配,但是自己写的也难保不会出错,所以就找了第三方...

  • 5
    • www.flydean.com 3 years ago
    • Cache

    ES9的新特性:正则表达式RegExp

    正则表达式是我们做数据匹配的时候常用的一种工具,虽然正则表达式的语法并不复杂,但是如果多种语法组合起来会给人一种无从下手的感觉。 于是正则表达式成了程序员的噩梦。今天我们来看一下如何在ES9中玩转正则表达式。 Numbered capture group...

  • 8

    pcre2el: convert between PCRE, Emacs and rx regexp syntax Overview pcre2el or rxt (RegeXp Translator or RegeXp Tools) is a utility for working with regular expressions in Emacs, based on a recur...

  • 4

    As I work on Zorex, an omnipotent regexp engine I have stumbled into a world of tales about why Unicode text sorting is so annoying in the modern day. Let’s talk about that. Why ASCII s...

  • 5

    如何解决 JavaScript 中 RegExp 不幂等的问题?在对 WXMarkdown 进行改造的时候,我准备使用 Vercel 提供的 cloudFunction 来实现。在执行时,出现了一个奇怪的问题,当我使用 RegExp 进行匹配的时候,会出现匹配成功和匹配失败的情况。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK