0
0

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.

【正規表現】後方参照は繰り返しではなく再利用

0
Posted at

初めてのPerl 第7版の p131 で少し混乱したのでメモします。

用語の整理

記号 名称 意味
/ / マッチ演算子
パターン マッチ演算子に囲まれた部分
( ) グループ パターンをまとめる
キャプチャグループ グループの中にマッチしたテキストを参照
\1、\2... 後方参照 マッチの際にキャプチャグループを利用

bbにマッチ

$_ = "abba";
if (/(.)\1/) {
    print "It matched same character next to itself!\n";
};

yabba dabbaにマッチ

$_ = "yabba dabba doo";
if (/y(....) d\1/) {
    print "It matched the same after y and d!\n";
};

\2は、2番目のグループ、すなわちbにマッチ
よって、yabbaにマッチ
量指定子と混同して、繰り返しだと思ってしまったのが個人的ハマりポイント

$_ = "yabba dabba doo";
if (/y(.)(.)\2\1/) {
    print "It matched!\n";
}

\3b\2aにマッチ
よって\1abbaにマッチ
したがってyabba dabbaにマッチ

$_ = "yabba dabba doo";
if (/y((.)(.)\3\2) d\1/) {
    print "It matched!\n"
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?