18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【CoffeeScript】正規表現リテラル内で変数を展開する

Posted at

CoffeeScriptにおける正規表現

Block Regular Expression

Rubyでは文字列と同じく,正規表現リテラル内でも変数展開が可能である.

`/#{hoge}Script/`

ではRubyと同様の文字列リテラルでの変数展開を利用できるCoffeeScriptだとどうか?

# これは死
# /#{hoge}Script/

# これならOK
///#{hoge}Script///

この3重スラッシュはBlock Regular Expressionsという名前らしい.

extended regular expressions that ignore internal whitespace and can contain comments and interpolation

Block Regular Expressions - CoffeeScript

///#{hoge}Script/// # =>`RegExp(hoge + "Script");` に変換される

Perlのxオプションのように改行とか空白,コメントも自由に入れられる(空白を無視してほしくない時はエスケープする: \ ).

Modeled after Perl's /x modifier

# 変換前
OPERATOR = /// ^ (
  ?: [-=]>             # function
   | [-+*/%<>&|^!?=]=  # compound assign / compare
   | >>>=?             # zero-fill right shift
   | ([-+:])\1         # doubles
   | ([&|<>])\2=?      # logic / shift
   | \?\.              # soak access
   | \.{2,3}           # range or splat
) ///

# 変換後
# var OPERATOR;
# 
# OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;

便利.

text = 'Java'
msg = 'JavaScriptTypeScriptCoffeeScriptTypeScriptJavaScriptCoffeeScript'

pattern = ///#{text}Script///g
msg.replace(pattern, 'TypeScript')
# => TypeScriptTypeScriptCoffeeScriptTypeScriptTypeScriptCoffeeScript

TypeScript最高(╹◡╹)

Ref

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?