目录

CoffeeScript - 正则表达式( Regular Expressions)

正则表达式是描述JavaScript支持的字符模式的对象。 在JavaScript中,RegExp类表示正则表达式,String和RegExp都定义了使用正则表达式在文本上执行强大的模式匹配和搜索和替换功能的方法。

CoffeeScript中的正则表达式

CoffeeScript中的正则表达式与JavaScript相同。 访问以下链接以查看JavaScript中的正则表达式javascript_regular_expressions

语法 (Syntax)

CoffeeScript中的正则表达式通过将RegExp模式放在正斜杠之间来定义,如下所示。

pattern =/pattern/

例子 (Example)

以下是CoffeeScript中正则表达式的示例。 在这里,我们创建了一个表达式,用于查找以粗体显示的数据(和 b>标记之间的数据)。 将此代码保存在名为regex_example.coffee的文件中

input_data ="hello how are you welcome to <b>IOWIKI.</b>"
regex = /<b>(.*)<\/b>/
result = regex.exec(input_data)
console.log result

打开command prompt并编译.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>IOWIKI.</b>";
  regex = /<b>(.*)<\/b>/;
  result = regex.exec(input_data);
  console.log(result);
}).call(this);

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee regex_example.coffee

执行时,CoffeeScript文件生成以下输出。

[ '<b>IOWIKI.</b>',
  'IOWIKI.',
  index: 29,
  input: 'hello how are you welcome to <b> IOWIKI.</b>' ]

heregex

我们使用JavaScript提供的语法编写的复杂正则表达式是不可读的,因此为了使正则表达式更具可读性,CoffeeScript为称为heregex正则表达式提供了扩展语法。 使用这种语法,我们可以使用空格来破坏正常的正则表达式,我们也可以在这些扩展的正则表达式中使用注释,从而使它们更加用户友好。

例子 (Example)

以下示例演示了CoffeeScript heregex中高级正则表达式的heregex 。 在这里,我们使用高级正则表达式重写上面的示例。 将此代码保存在名为heregex_example.coffee的文件中

input_data ="hello how are you welcome to <b class="notranslate">IOWIKI.</b>"
heregex = ///
<b>  #bold opening tag 
(.*) #the tag value
</b>  #bold closing tag
///
result = heregex.exec(input_data)
console.log result

打开command prompt并编译.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> IOWIKI.</b>";
  heregex = /<b>(.*) <\/b>/;
  result = heregex.exec(input_data);
  console.log(result);
}).call(this);

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee heregex_example.coffee

执行时,CoffeeScript文件生成以下输出。

[ '<b>IOWIKI.</b>',
  'IOWIKI.',
  index: 29,
  input: 'hello how are you welcome to <b>IOWIKI.</b>' ]
↑回到顶部↑
WIKI教程 @2018