CoffeeScript - 正則表示式



正則表示式是一個描述JavaScript支援的字元模式的物件。在JavaScript中,RegExp類表示正則表示式,String和RegExp都定義了使用正則表示式對文字執行強大的模式匹配和搜尋替換功能的方法。

CoffeeScript中的正則表示式

CoffeeScript中的正則表示式與JavaScript相同。訪問以下連結檢視JavaScript中的正則表示式:javascript_regular_expressions

語法

CoffeeScript中的正則表示式透過將RegExp模式放在正斜槓之間來定義,如下所示。

pattern =/pattern/

示例

以下是CoffeeScript中正則表示式的示例。在這裡,我們建立了一個表示式,用於查詢以粗體顯示的資料(<b>和</b>標記之間的資料)。將此程式碼儲存在名為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>' ]

heregex

我們使用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>' ]
廣告