正規表現は、コンピュータープログラミングではかなり一般的です。ただし、エンドユーザーも利用できます。たとえば、PowerShellまたはFindstrコマンドを扱っている場合は、それらを利用できます。また、正規表現をサポートするサードパーティのユーティリティ(Agent RansackやEditPadなど)があります。それらは多くの異なる環境で非常に役立つので、私はそれらについてのヒントが適切であると判断しました。

正規表現は、検索パターンに一致するように設計された、多くの場合特殊文字で構成される文字列です。たとえば、Findstrコマンドを使用している場合、「ドキュメント」という単語を検索できます

検索文字列「document [,.]」を指定して、直後にコンマまたはピリオドを入力します。この場合の特殊文字は角括弧です。これは、囲まれた文字のいずれかが「ドキュメント」という単語の後に続く必要があることを意味します。

正規表現で使用できる特殊文字はたくさんあります。その多くを以下に示します:

Character

Description

Match 0 or more characters. Example: haven matches both heaven

and haven.

+

Match 1 or more characters. Example: he+aven matches heaven and

heeaven but not haven.

^

Match what follows only if it’s at the beginning of the string.

Example: if your regular expression is ^document, it will match document

in the string “document the requirements”, but it will not match

anything in the string “this is a requirements document”.

$

Match what precedes only if it’s at the end of the string.

Example: if your regular expression is document$, it will match document

in the string “this is a requirements document”, but it will not match

anything in the string “document the requirements”.

\d

Match a digit. Example: \d matches each digit individually in

the string “my degree is from 1987”. If you want to match all four

digits at once, just repeat the \d like \d\d\d\d.

.

Match any single character. The period is like a wildcard in that

it will match anything.

(a

b)

正規表現の動作を確認するには、いくつかを組み合わせて、Findstrコマンドを使用してファイル内の文字列の出現を検索します。次のテキストを含むBarry.tmpというファイルがあります:

Video provides a powerful way to help you prove your point.  When you click Online Video, you can paste in the embed code for  the 20 or 30 videos you want to add. You can also type a keyword  to search online for the video that best fits your document.

Findstrを使用して、ファイル内の数字の文字列を検索してみましょう:(図1を参照)

image

図1.数字の文字列の検索。

他のいくつかの概念を紹介します。角かっこを使用して、検出する文字の範囲を区切ることができます。たとえば、_ [a-z] _を指定すると、任意の英字に一致します。また、バックスラッシュ文字(\)を使用して、後続の文字を「エスケープ」し、文字通りに処理することも注目に値します。これは、正規表現の一部として扱われる文字を検索する場合に役立ちます。これらの2つの情報を利用して、ファイルでアルファベット文字とそれに続くピリオドを検索できます。つまり、文の終わりである行を見つけることができます:(図2を参照)

image

図2.文の終わりの検索。

最後に注意が必要です。私の経験では、Windowsコマンドラインで使用される正規表現エンジンは、ほとんどの正規表現エンジンとは少し異なります。動作するはずの(そして他のユーティリティで動作する)正規表現は、コマンドラインで期待どおりに動作しない場合があります。したがって、マイレージが異なる可能性があることを知って、それらを試してみてください。ただし、入力した内容が期待どおりに機能することを次の給与に賭けないでください。

このヒント(1364)は、Windows 7、8、および10に適用されます。