Next: , Previous: , Up: 正規表現   [Contents][Index]


35.3.2 正規表現の複雑な例

以下は後続の空白文字とともにセンテンスの終わりを認識するために、以前のEmacsで使用されていた複雑な正規表現の例です(現在のEmacsは関数sentence-endにより構築される、同様のより複雑なregexpを使用する。編集で使用される標準的な正規表現を参照)。

以下ではまず、(スペースとタブ文字を区別するために)Lisp構文の文字列としてregexpを示して、それを評価した結果を示します。文字列定数の開始と終了はダブルクォーテーションです。‘\"’は文字列の一部としてのダブルクォーテーション、‘\\’は文字列の一部としてのバックスラッシュ、‘\t’はタブ、‘\n’は改行を意味します。

"[.?!][]\"')}]*\\($\\| $\\|\t\\|  \\)[ \t\n]*"
     ⇒ "[.?!][]\"')}]*\\($\\| $\\|  \\|  \\)[
]*"

改行とタブは、それら自身として出力されます。

この正規表現は連続する4つのパートを含み、以下のように解読できます:

[.?!]

The first part of the pattern is a bracket expression that matches any one of three characters: period, question mark, and exclamation mark. The match must begin with one of these three characters. (This is one point where the new default regexp used by Emacs differs from the old. The new value also allows some non-ASCII characters that end a sentence without any following whitespace.)

[]\"')}]*

The second part of the pattern matches any closing braces and quotation marks, zero or more of them, that may follow the period, question mark or exclamation mark. The \" is Lisp syntax for a double-quote in a string. The ‘*’ at the end indicates that the immediately preceding regular expression (a bracket expression, in this case) may be repeated zero or more times.

\\($\\| $\\|\t\\|  \\)

パターンの3つ目のパートはセンテンスの後の空白文字、すなわち行の終端(スペースがあっても可)、タブ、または2つのスペースにマッチする。2連バックスラッシュはカッコと垂直バーを正規表現構文としてマークする。すなわちカッコはグループを句切り、垂直バーは選択肢を区別する。ダラー記号は行の終端へのマッチに使用される。

[ \t\n]*

最後にパターンの最終パートはセンテンスを終端させるために必要とされる以上の、余分な空白文字にマッチする。

rx (rx構造化Rgexp表記を参照)表記では以下のようにregexpを記述できます

(rx (any ".?!")                    ; センテンスを終端する区切り文字
    (zero-or-more (any "\"')]}"))  ; 終わりのクォートやカッコ
    (or line-end
        (seq " " line-end)
        "\t"
        "  ")                      ; 2つのスペース
    (zero-or-more (any "\t\n ")))  ; オプションの余分な空白文字

rxによるregexpsは単なるS式なので、このように整形してコメントを付することができるのです。

This page has generated for branch:master, commit:762705fb24fd90db318f2e51c1e762452d26f7e2 to check Japanese translation.