CoffeeScript 正则表达式
正则表达式是描述 JavaScript 支持的字符模式的对象。在 JavaScript 中,RegExp 类表示正则表达式,String 和 RegExp 都定义了使用正则表达式对文本执行强大的模式匹配和搜索替换功能的方法。
CoffeeScript 中的正则表达式
CoffeeScript 中的正则表达式与 JavaScript 相同。访问以下链接以查看 JavaScript 中的正则表达式-javascript_regular_expressions
语法
CoffeeScript 中的正则表达式是通过在正斜杠之间放置 RegExp 模式来定义的,如下所示。
示例
以下是 CoffeeScript 中的正则表达式示例。在这里,我们创建了一个表达式,用于找出粗体数据(
和 标记之间的数据)。将此代码保存在名为
regex_example.coffee的文件中
input_data ="hello how are you welcome to <b>Tutorials Point.</b>"
regex = /<b>(.*)<\/b>/
result = regex.exec(input_data)
console.log result
打开
命令提示符并编译.coffee文件,如下所示。
c:\> coffee-c regex_example.coffee
在编译时,它会为您提供以下 JavaScript。
// Generated by CoffeeScript 1.10.0
(function() {
var input_data, regex, result;
input_data = "hello how are you welcome to <b>Tutorials Point.</b>";
regex = /<b>(.*)<\/b>/;
result = regex.exec(input_data);
console.log(result);
}).call(this);
现在,再次打开
命令提示符并运行CoffeeScript文件,如下所示。
c:\> coffee regex_example.coffee
执行时,CoffeeScript 文件产生以下输出。
[ '<b>Tutorials Point.</b>',
'Tutorials Point.',
index: 29,
input: 'hello how are you welcome to <b> Tutorials Point.</b>' ]
正则表达式
我们使用 JavaScript 提供的语法编写的复杂正则表达式是不可读的,因此为了使正则表达式更具可读性,CoffeeScript 为正则表达式提供了一种扩展语法,称为
heregex。使用这种语法,我们可以使用空格打破常规的正则表达式,我们也可以在这些扩展的正则表达式中使用注释,从而使它们更加用户友好。
示例
以下示例演示了 CoffeeScript
heregex 中高级正则表达式的用法。在这里,我们使用高级正则表达式重写上面的示例。将此代码保存在名为
heregex_example.coffee的文件中
input_data ="hello how are you welcome to Tutorials Point."
heregex = ///
<b> #bold opening tag
(.*) #the tag value
</b> #bold closing tag
///
result = heregex.exec(input_data)
console.log result
打开
命令提示符并编译.coffee文件,如下所示。
c:\> coffee-c heregex_example.coffee
在编译时,它会为您提供以下 JavaScript。
// Generated by CoffeeScript 1.10.0
(function() {
var heregex, input_data, result;
input_data = "hello how are you welcome to <b> Tutorials Point.</b>";
heregex = /<b>(.*) <\/b>/;
result = heregex.exec(input_data);
console.log(result);
}).call(this);
现在,再次打开
命令提示符并运行CoffeeScript文件,如下所示。
c:\> coffee heregex_example.coffee
执行时,CoffeeScript 文件产生以下输出。
[ '<b>Tutorials Point.</b>',
'Tutorials Point.',
index: 29,
input: 'hello how are you welcome to <b>Tutorials Point.</b>' ]