博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用JavaScript进行反向查询
阅读量:2515 次
发布时间:2019-05-11

本文共 2164 字,大约阅读时间需要 7 分钟。

I've always loved exploring regular expressions because they're one of those skills that's never taught in school -- you need to pick them up on the fly, messing up and fixing them along the way. Regex's are incredibly powerful, and one power they have are referred to as backreferences, which essentially allow you to use a match within the same regular expression.

我一直很喜欢探索正则表达式,因为它们是学校从未教过的那些技能之一-您需要即时获取它们,弄乱它们并一路搞定。 正则表达式非常强大,它们的一种功能称为反向引用,它实际上使您可以在同一正则表达式中使用匹配项。

The easiest way to explain a backreference is with a simple goal: using a regex to simulate destructuring. Take the following code snippet:

解释反向引用的最简单方法是一个简单的目标:使用正则表达式来模拟解构。 采取以下代码段:

const body = document.blah.body;

With an awesome new language feature like , a better way to write the code above is:

借助等令人敬畏的新语言功能,编写上面代码的更好方法是:

const { body } = document.blah;

Note: As a general programming rule, using regular expressions to implement or simulate language features is a very bad idea.  For the sake of explaining backreferences, however, it's perfect.

注意:作为一般的编程规则,使用正则表达式实现或模拟语言功能是一个非常糟糕的主意。 但是,为了解释反向引用,它是完美的。

The backreference syntax is \{number of match}:

反向引用语法为\{number of match}

const code = "const body = document.blah.body;";const destrcutured = code.replace(/const (\w+) = ([A-z\.]+)\.\1;/, "const { $1 } = $2;");// const { body } = document.blah";

In the example above, we use \1 to refer to the first match within the same expression. We then use $1 to reflect the matched (\w+) and $2 to reflect the object chain (([A-z.]+)). You can use any number of backreferences with \{#} syntax. Be aware that backreferencing is taxing on performance: some utilities like VS Code wont support them; Atom editor does support backreferencing.

在上面的示例中,我们使用\1引用同一表达式中的第一个匹配项。 然后,我们使用$1反映匹配的(\w+)$2反映对象链( ([Az.]+) )。 您可以使用\{#}语法使用任意数量的反向引用。 请注意,反向引用会影响性能:某些工具(如VS Code)将不支持它们;它们会影响性能。 Atom编辑器确实支持反向引用。

Regular expressions are always an adventure and there's always more to learn. My favorite part of regular expressions is how a single character can drastically change the result -- such power in a condensed amount of code!

正则表达式始终是一种冒险,总是有很多东西要学习。 我最喜欢的正则表达式部分是单个字符如何极大地改变结果-精简代码中的强大功能!

翻译自:

转载地址:http://rfvwd.baihongyu.com/

你可能感兴趣的文章
Laravel框架学习笔记之任务调度(定时任务)
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
jxl写入excel实现数据导出功能
查看>>
linux文件目录类命令|--cp指令
查看>>
.net MVC 404错误解决方法
查看>>
linux系统目录结构
查看>>
git
查看>>
btn按钮之间事件相互调用
查看>>
Entity Framework 4.3.1 级联删除
查看>>
codevs 1163:访问艺术馆
查看>>
冲刺Noip2017模拟赛3 解题报告——五十岚芒果酱
查看>>
并查集
查看>>
sessionStorage
查看>>
代码示例_进程
查看>>
Java中关键词之this,super的使用
查看>>
学习进度
查看>>