CoffeeScript 字串 - match()



描述

在使用正則表示式匹配字串時使用此方法進行匹配。其工作方式類似於 regexp.exec(string),但沒有 g 標誌,它會以 g 標誌返回包含所有匹配項的陣列。

語法

以下是 JavaScript 的 match() 方法的語法。我們可以在 CoffeeScript 程式碼中使用相同的方法。

string.match( param )

示例

下面的示例演示瞭如何在 CoffeeScript 程式碼中使用 JavaScript 的 match() 方法。將此程式碼另存為副檔名為 string_localecompare.coffee 的檔案

str = "For more information, see Chapter 3.4.5.1";
re = /(chapter \d+(\.\d)*)/i;
found = str.match re
         
console.log found 

開啟 命令提示符,並按如下所示編譯 .coffee 檔案。

c:\> coffee -c coffee string_match.coffee

編譯後,它會生成以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var found, re, str;

  str = "For more information, see Chapter 3.4.5.1";

  re = /(chapter \d+(\.\d)*)/i;

  found = str.match(re);

  console.log(found);

}).call(this);

現在,再次開啟 命令提示符,並按如下所示執行 CoffeeScript 檔案。

c:\> coffee string_match.coffee 

執行時,CoffeeScript 檔案生成以下輸出。

[ 'Chapter 3.4.5.1',
  'Chapter 3.4.5.1',
  '.1',
  index: 26,
  input: 'For more information, see Chapter 3.4.5.1' ]
coffeescript_strings.htm
廣告