使用JavaScript进行反向查询

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 JavaScript destructuring, a better way to write the code above is:

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

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!

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

翻译自: https://davidwalsh.name/javascript-backreference-regex

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值