As a SW/Ops/DB Engineer

riywo’s technology memo

Multiple Assignment From Regexp

Sometimes I want to assign multiple variables from results of regexp matching. Here are the ways in some LLs.

Perl

my ($a, $b) = ("a:1 b:2" =~ /a:(\d) b:(\d)/);
# or
my ($a, $b) = "a:1 b:2" =~ /a:(\d) b:(\d)/;

Ruby

a, b = "a:1 b:2".match(/a:(\d) b:(\d)/) {[$1, $2]}
# or
a, b = "a:1 b:2".match(/a:(\d) b:(\d)/).to_a[1, 2]

Python

import re
a, b = re.match(r'a:(\d) b:(\d)', "a:1 b:2").group(1, 2)

Conclusion

  • Perl
    • simplest
    • needs parentheses for multiple assignment
      • parentheses for matching are not mandatory, though
  • Ruby
    • match is a method of String class
    • give a block or slice an array
  • Python
    • needs re module
    • match is a method of re

Enjoy!


簡単にファイルをパースしたい時とかに、Perlで書いた正規表現でさくっと変数に多重代入したりしてたんですが、Ruby/Pythonだとどうやるのか分からなかったのでまとめ。Thanks to @_shimada, @methane, @kyoendo, @toku_bass

namedcapture版も作ってみたい。というかそもそもオレオレLL比較チートシート作りたい。

Comments