
- CoffeeScript 教程
- CoffeeScript - 首頁
- CoffeeScript - 概述
- CoffeeScript - 環境
- CoffeeScript - 命令列工具
- CoffeeScript - 語法
- CoffeeScript - 資料型別
- CoffeeScript - 變數
- CoffeeScript - 運算子和別名
- CoffeeScript - 條件語句
- CoffeeScript - 迴圈
- CoffeeScript - 列表推導式
- CoffeeScript - 函式
- CoffeeScript 面向物件程式設計
- CoffeeScript - 字串
- CoffeeScript - 陣列
- CoffeeScript - 物件
- CoffeeScript - 範圍
- CoffeeScript - 展開運算子
- CoffeeScript - 日期
- CoffeeScript - 數學
- CoffeeScript - 異常處理
- CoffeeScript - 正則表示式
- CoffeeScript - 類和繼承
- CoffeeScript 高階特性
- CoffeeScript - Ajax
- CoffeeScript - jQuery
- CoffeeScript - MongoDB
- CoffeeScript - SQLite
- CoffeeScript 有用資源
- CoffeeScript - 快速指南
- CoffeeScript - 有用資源
- CoffeeScript - 討論
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>' ]