Coffeescript-regular-expressions

提供:Dev Guides
移動先:案内検索

CoffeeScript-正規表現

正規表現は、JavaScriptがサポートする文字のパターンを記述するオブジェクトです。 JavaScriptでは、RegExpクラスは正規表現を表し、StringとRegExpの両方が、正規表現を使用してテキストの強力なパターンマッチングおよび検索と置換機能を実行するメソッドを定義します。

CoffeeScriptの正規表現

CoffeeScriptの正規表現はJavaScriptと同じです。 JavaScriptでの正規表現を確認するには、次のリンクにアクセスしてください-リンク:/javascript/javascript_regexp_object [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>' ]

異端者

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>' ]