各種LLで正規表現でマッチした結果を一発で変数に代入したい
ES6のDestructuring assignmentの使い方で良い例があったのでメモ。
正規表現でキャプチャした結果を変数に突っ込むという使い方です。
JavaScript(Babelが必要・・・)
const string = '20150925'; const [, y, m, d] = /(\d{4})(\d{2})(\d{2})/.exec(string); // 0番目は捨てる console.log(`${y}年${m}月${d}日`);
↓以下、Perl以外自信ないですが、一応。
use feature 'say'; my $string = '20150925'; my ($y, $m, $d) = $string =~ /(\d{4})(\d{2})(\d{2})/; say "$y年$m月$d日";
string = '20150925' y, m, d = string.match(/(\d{4})(\d{2})(\d{2})/).captures puts "#{y}年#{m}月#{d}日"
# -*- coding: utf-8 -*- import re string = "20150925" y, m, d = re.search(r"(\d{4})(\d{2})(\d{2})", string).groups() print u"%s年%s月%s日" % (y, m, d)