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