Coffeescript 正则表达式插值 [英] Coffeescript Regex interpolation

查看:15
本文介绍了Coffeescript 正则表达式插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Coffeescript 支持字符串插值:

Coffeescript supports strings interpolation:

user = "world"
greeting = "Hello #{user}!"

是否可以像在字符串中一样在正则表达式中使用插值?例如.

Is it possible to use interpolation in regex just like in strings? E.g.

regex = /Hello #{user}/g

附:我知道我可以使用 RegExp(greeting, 'g'),我只是想要更简洁的代码.

P.S. I know that I can use RegExp(greeting, 'g'), I just want a bit cleaner code.

推荐答案

块正则表达式(Heregexes)支持插值.

Block Regular Expressions (Heregexes) support interpolation.

类似于阻止字符串和注释,CoffeeScript 支持块正则表达式——扩展正则表达式忽略内部空格并且可以包含注释和插值.模仿 Perl 的/x 修饰符,CoffeeScript 的块正则表达式由///分隔,并且对复杂化大有帮助正则表达式可读.

Block Regular Expressions

Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl's /x modifier, CoffeeScript's block regexes are delimited by /// and go a long way towards making complex regular expressions readable.

这个咖啡脚本代码:

name="hello"
test=///#{name}///

编译成

var name, test;

name = "hello";

test = RegExp("" + name);

这篇关于Coffeescript 正则表达式插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆