TryHackMe 歴1ヵ月半が参加する Advent of Cyber 2022 [Day 17]

17 日目。

[Day 17] Filtering for Order Amidst Chaos

今回は正規表現のお話。

Filtering for Usernames: How many usernames fit the syntax above?

ターミナルを開いて ~/Desktop/RegExPractice ディレクトリに移動すると regex_checker.pystrings の 2 つのファイルが見える。strings ファイルの中身を正規表現を用いて絞っていこうというのが今回の課題である。

問題を解くにあたって、egep コマンドを用いる方法と regex_checker.py を用いる方法が提示されているが、せっかくスクリプトを用意してくれたので今回は後者で解いていく。

まずはユーザ名を絞る。

Filtering for Usernames: Alphanumeric, minimum of 6 characters, maximum of 12 characters, may consist of upper and lower case letters.

英数字 6-12 文字のものを絞るので、その通りに正規表現を書く。^$ をお忘れなく。^[a-zA-Z0-9]{6,12}$ で結果が出るのであとはそれを数えて回答する。

Filtering for Usernames: One username consists of a readable word concatenated with a number. What is it?

前問の結果から、単語をなしているかつ数字が連結しているユーザ名を回答する。

Filtering for Emails: How many emails fit the syntax above?

お次はメールアドレスを絞る。

Filtering for Emails: Follows the form "local-part@domain" (without quotation marks); local-part is a random string, and the domain is in the form of ".tld". All top-level domains (tld) are ".com"

local-part の random string というのがどこまで許容されるのかわからなかったので grep コマンドを使って邪道解きをした。一番上の ~@.com というのはメールアドレスっぽくはないのでそれ以外の結果の数を回答。そうすると正解だったのでまぁよしとした。

正攻法で解きたい人向け

上の結果を見るに、local-part は英数字とドットが許容されるようなので、正規表現を書くなら ^[a-zA-Z0-9.]+@[a-zA-Z]+\.com$ となる。なお、[] 内ではドットはエスケープしなくてもいいらしい。

Filtering for Emails: How many unique domains are there?

要は上の結果から何種類のドメインが使われているかを答える、という問題。数えるだけ。

Filtering for Emails: What is the domain of the email with the local-part "lewisham44"?

結果を見て答える。

Filtering for Emails: What is the domain of the email with the local-part "maxximax"?

結果を見て答える。

Filtering for Emails: What is the local-part of the email with the domain name "hotmail.com"?

結果を見て答える。

Filtering for URLs: How many URLs fit the syntax provided?

最後は URL を絞る。

Filtering for URLs: Starts with either http or https; some of the URLs have "www", and a TLD should exist.

https の s は ? を用いて対処する。www はあってもなくてもよいみたいなので無視する。TLD が必要なので途中でドットが入るようにする。以降どのような形でもいいようなので最後の $ は今回は用いない。正規表現^https?://[a-zA-Z0-9]+\.[a-zA-Z] となる。

Filtering for URLs: How many of these URLs start with "https"?

結果を見て答える。

If you feel like you could use more fundamental skills in your life, try the Linux Fundamentals module. All rooms are free in that one!

No answer needed

感想

正規表現の難しさは単に使い方が覚えられないという点もあるが、やはりその表現の多さにあると思う。今回の記事を読んで「自分の作った正規表現と違う!」なんてことは普通にありえる。正直自分の書いた正規表現なんてとてもじゃないが実践で使えないなぁと常に思いながら書いてる部分はある。今回も同様で、たぶんガバガバなんだろうなぁと。