7
5

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.

【正規表現の理解に便利】正規表現にマッチする文字列を作成して、返してくれる Gem

Last updated at Posted at 2016-05-30

regexp-examples

/\wuby/.examples
# => ["auby", "buby", "cuby", "duby", "euby"]
/\wuby/.random_example
# => "Guby"

Regexp クラスを拡張して、正規表現にマッチする文字列を返す examples, random_example メソッドを定義する Gem。

ちなみに、examples は(繰り返し文字には制限がありますが)全てのマッチするパターンを返してくれて、random_example は全てのパターンから一つ sample で返してくれるメソッドです。
ぱっと見で分かりづらい正規表現の理解や、自分が作った正規表現が正しいかどうかを確認するのにとても便利そうですね。

オプション

上で examples は繰り返し文字に制限があると書きましたが、繰り返す文字数や文字種はオプションで指定することが出来ます。

指定できるオプションは

  • max_repeater_variance
  • max_group_results
  • max_results_limit

の 3 種類です。

max_repeater_variance (default = 2)

max_repeater_variance は繰り返しする文字数の長さを指定します。
例えば、デフォルト 2 なので、.* は 全ての文字数を 0-2 回繰り返します。

/a*/.examples #=> ["", "a", "aa"]
/[ab]*/.examples #=> ["", "a", "b", "aa", "ab", "ba", "bb"]
/[ab]*/.examples(max_repeater_variance: 3)
# => ["", "a", "b", "aa", "ab", "ba", "bb", "aaa", "aab", "aba", "abb", "baa", "bab", "bba", "bbb"]

/a+/.examples #=> ["a", "aa", "aaa"]
/a+/.examples(max_repeater_variance: 3) #=> ["a", "aa", "aaa", "aaaa"]

max_group_results (default = 5)

\d[1-9] は数値、\w[a-zA-Z0-9] は英数字、というように正規表現は全てを表記しなくとも、まとめて値を指定する事が出来ますが、これらの group のうち何種類の結果を返すかを指定する事が出来ます。

具体例を上げると

/\d/.examples #=> ["0", "1", "2", "3", "4"]
/[a-z]/.examples #=> ["a", "b", "c", "d", "e"]
/[c-n]/.examples #=> ["c", "d", "e", "f", "g"]

/\d/.examples(max_group_results: 6) #=> ["0", "1", "2", "3", "4", "5"]
/\w/.examples(max_group_results: 10) #=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

このようになります。

max_results_limit (default = 10000)

最後の max_results_limit は、最終的な結果の max サイズを指定します。

/\d/.examples #=> ["0", "1", "2", "3", "4"]
/\d/.examples(max_results_limit: 2) #=> ["0", "1"]
/\d/.examples(max_results_limit: 10) #=> ["0", "1", "2", "3", "4"]

以上が指定できるオプションです。
これらを組み合わせれば、かなりの種類の具体例を出力出来ますね。

普通に正規表現を理解するのにも便利だけど、何か sample データをさくっと用意したり、正規表現をテストしたり、いろいろな用途に使えそう。

/
  \u{28}\u2022\u{5f}\u2022\u{29}
  |
  \u{28}\u{20}\u2022\u{5f}\u2022\u{29}\u{3e}\u2310\u25a0\u{2d}\u25a0\u{20}
  |
  \u{28}\u2310\u25a0\u{5f}\u25a0\u{29}
/x.examples
# => ["(•_•)", "( •_•)>⌐■-■ ", "(⌐■_■)"]

便利!

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?