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

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

问题描述

Coffeescript支持字符串插值:

Coffeescript supports strings interpolation:

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

是否可以像在字符串中一样在regex中使用插值?例如。

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

regex = /Hello #{user}/g

PS我知道我可以使用 RegExp(greetings,'g'),我只是想要一个更干净的代码。

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

推荐答案

阻止正则表达式(Heregexes)支持插值。

Block Regular Expressions (Heregexes) support interpolation.


b
$ b

与块字符串和注释类似,
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.

这个coffeescript代码:

This coffeescript code:

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

编译为

var name, test;

name = "hello";

test = RegExp("" + name);

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

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