Skip to content

Instantly share code, notes, and snippets.

@gfx
Last active September 17, 2017 21:57
Show Gist options
  • Save gfx/7973689 to your computer and use it in GitHub Desktop.
Save gfx/7973689 to your computer and use it in GitHub Desktop.
正規表現リテラルがあると便利な例。これを文字列操作メソッドで解決するとなるとかなり難しいと思われますがどうでしょう。 また、正規表現リテラルがなくてもじっさいにはあまり変わりないのですが、 \S ではなく \\S と書かなければならなかったりして注意しなければならない点が増えます。
#!perl
use 5.10.0;
use strict;
use warnings;
my $localhost = join '|', map { quotemeta } 'localhost', '127.0.0.1';
my $s = "http://localhost/foo http://127.0.0.1/bar http://127_0_0_1/foo/bar/baz";
my @matched = $s =~ m{ http:// (?:$localhost) / \S+ }xg;
say "@matched"; # => http://localhost/foo http://127.0.0.1/bar
@gfx
Copy link
Author

gfx commented Dec 16, 2013

正規表現リテラルにおける変数展開の重要性についてはたびたび出していたつもりでしたが、その点説明不足であったのならすみません。たとえばJavaScriptは正規表現リテラルがあって変数展開のない言語ですが、これは非常に使いづらくリテラルだけあっても意味がないとぼくは考えます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment