バージョンごとのドキュメント一覧

9.7. パターンマッチ #

<title>Pattern Matching</title>

There are three separate approaches to pattern matching provided by <productname>PostgreSQL</productname>: the traditional <acronym>SQL</acronym> <function>LIKE</function> operator, the more recent <function>SIMILAR TO</function> operator (added in SQL:1999), and <acronym>POSIX</acronym>-style regular expressions. Aside from the basic <quote>does this string match this pattern?</quote> operators, functions are available to extract or replace matching substrings and to split a string at matching locations. PostgreSQLには、パターンマッチを行うに際して3つの異なった手法があります。伝統的なSQLLIKE演算子、これより新しいSIMILAR TO演算子(SQL:1999で追加されました)、およびPOSIX様式の正規表現です。 基本のこの文字列はこのパターンに一致するか?を別としても、一致した部分文字列を取り出したり置換したり、そして一致部分で文字列を分割する関数が用意されています。

ヒント

If you have pattern matching needs that go beyond this, consider writing a user-defined function in Perl or Tcl. 上記の手法では検索できないようなパターンマッチが必要な場合は、PerlもしくはTclでユーザ定義関数を作成することを検討してください。

注意

While most regular-expression searches can be executed very quickly, regular expressions can be contrived that take arbitrary amounts of time and memory to process. Be wary of accepting regular-expression search patterns from hostile sources. If you must do so, it is advisable to impose a statement timeout. ほとんどの正規表現検索はとても速く実行されますが、正規表現は処理するのに任意の時間とメモリを使う可能性があります。 悪意のあるソースから正規表現検索パターンを受け取ることに用心してください。 そうしなければならないのであれば、文のタイムアウトを強制するのが賢明です。

Searches using <function>SIMILAR TO</function> patterns have the same security hazards, since <function>SIMILAR TO</function> provides many of the same capabilities as <acronym>POSIX</acronym>-style regular expressions. SIMILAR TOPOSIX書式の正規表現と同じ多くの機能を提供するので、SIMILAR TOパターンを使う検索は同様のセキュリティ問題を抱えています。

<function>LIKE</function> searches, being much simpler than the other two options, are safer to use with possibly-hostile pattern sources. LIKE検索は、他の2つの方法よりずっと単純ですので、悪意があるかもしれないパターンのソースで使うのにはより安全です。

The pattern matching operators of all three kinds do not support nondeterministic collations. If required, apply a different collation to the expression to work around this limitation. この3種類のパターンマッチング演算子はどれも非決定的照合順序をサポートしていません。 必要なら、この制限事項に対応するために別の照合順序を式に適用してください。

9.7.1. LIKE #

string LIKE pattern [ESCAPE escape-character]
string NOT LIKE pattern [ESCAPE escape-character]

The <function>LIKE</function> expression returns true if the <replaceable>string</replaceable> matches the supplied <replaceable>pattern</replaceable>. (As expected, the <function>NOT LIKE</function> expression returns false if <function>LIKE</function> returns true, and vice versa. An equivalent expression is <literal>NOT (<replaceable>string</replaceable> LIKE <replaceable>pattern</replaceable>)</literal>.) LIKE式は供給されたpatternstringが一致すれば真を返します。 (想像される通り、NOT LIKE式はLIKE式が真を返す場合には偽を返し、その逆もまた同じです。 同等の式としてNOT (string LIKE pattern)とも表現できます。)

If <replaceable>pattern</replaceable> does not contain percent signs or underscores, then the pattern only represents the string itself; in that case <function>LIKE</function> acts like the equals operator. An underscore (<literal>_</literal>) in <replaceable>pattern</replaceable> stands for (matches) any single character; a percent sign (<literal>%</literal>) matches any sequence of zero or more characters. patternがパーセント記号もしくはアンダースコアを含んでいない場合patternは自身の文字列そのものです。この場合LIKE式は等号演算子のように振舞います。 patternの中にあるアンダースコア(_)は任意の一文字との一致を意味し、パーセント記号(%)は0文字以上の並びとの一致を意味します。

Some examples: 例:

'abc' LIKE 'abc'    true
'abc' LIKE 'a%'     true
'abc' LIKE '_b_'    true
'abc' LIKE 'c'      false

<function>LIKE</function> pattern matching always covers the entire string. Therefore, if it's desired to match a sequence anywhere within a string, the pattern must start and end with a percent sign. LIKEによるパターン一致は常に文字列全体に対して行われます。 従って、文字列内の任意位置における並びと一致させたい場合には、パーセント記号を先頭と末尾に付ける必要があります。

To match a literal underscore or percent sign without matching other characters, the respective character in <replaceable>pattern</replaceable> must be preceded by the escape character. The default escape character is the backslash but a different one can be selected by using the <literal>ESCAPE</literal> clause. To match the escape character itself, write two escape characters. 他の文字の一致に使用するのではなく、アンダースコアやパーセント記号そのものを一致させたい場合には、patternの中のそれぞれのアンダースコアとパーセント記号の前にエスケープ文字を付けなければなりません。 デフォルトのエスケープ文字はバックスラッシュですが、ESCAPE句で他の文字を指定することができます。エスケープ文字そのものを一致させるにはエスケープ文字を2つ書きます。

注記

If you have <xref linkend="guc-standard-conforming-strings"/> turned off, any backslashes you write in literal string constants will need to be doubled. See <xref linkend="sql-syntax-strings"/> for more information. standard_conforming_stringsパラメータをoffにしている場合、リテラル文字列定数に記述するバックスラッシュを二重にする必要があります。 詳細は4.1.2.1を参照してください。

It's also possible to select no escape character by writing <literal>ESCAPE ''</literal>. This effectively disables the escape mechanism, which makes it impossible to turn off the special meaning of underscore and percent signs in the pattern. 同時にESCAPE ''と記述することでエスケープ文字を選択しないことも可能です。 これにより、事実上エスケープ機構が働かなくなります。つまり、パターン内のアンダースコアおよびパーセント記号の特別な意味を解除することはできなくなります。

According to the SQL standard, omitting <literal>ESCAPE</literal> means there is no escape character (rather than defaulting to a backslash), and a zero-length <literal>ESCAPE</literal> value is disallowed. <productname>PostgreSQL</productname>'s behavior in this regard is therefore slightly nonstandard. SQL標準によれば、ESCAPEを省略することは(デフォルトがバックスラッシュとなるのではなく)エスケープ文字が存在しないことを意味します。長さゼロのESCAPEは使用できません。 ですからこの点でPostgreSQLは少し非標準な振る舞いをします。

The key word <token>ILIKE</token> can be used instead of <token>LIKE</token> to make the match case-insensitive according to the active locale. This is not in the <acronym>SQL</acronym> standard but is a <productname>PostgreSQL</productname> extension. 現在のロケールに従って大文字小文字を区別しない一致を行うのであれば、LIKEの代わりにILIKEキーワードを使うことができます。 これは標準SQLではなく、PostgreSQLの拡張です。

The operator <literal>~~</literal> is equivalent to <function>LIKE</function>, and <literal>~~*</literal> corresponds to <function>ILIKE</function>. There are also <literal>!~~</literal> and <literal>!~~*</literal> operators that represent <function>NOT LIKE</function> and <function>NOT ILIKE</function>, respectively. All of these operators are <productname>PostgreSQL</productname>-specific. You may see these operator names in <command>EXPLAIN</command> output and similar places, since the parser actually translates <function>LIKE</function> et al. to these operators. ~~演算子はLIKE式と等価で、~~*ILIKEに対応します。 またNOT LIKEおよびNOT ILIKEを表す!~~および!~~*演算子があります。 これら全ての演算子はPostgreSQL固有のものです。 パーサは実際にはLIKEなどをこれらの演算子に変換するため、こうした演算子名はEXPLAINの出力などで見ることができます。

The phrases <function>LIKE</function>, <function>ILIKE</function>, <function>NOT LIKE</function>, and <function>NOT ILIKE</function> are generally treated as operators in <productname>PostgreSQL</productname> syntax; for example they can be used in <replaceable>expression</replaceable> <replaceable>operator</replaceable> ANY (<replaceable>subquery</replaceable>) constructs, although an <literal>ESCAPE</literal> clause cannot be included there. In some obscure cases it may be necessary to use the underlying operator names instead. LIKEILIKENOT LIKENOT ILIKE句は一般にPostgreSQLの構文上は演算子として扱われます。 たとえば、 演算子 ANY(副問い合わせ)構文で使用できます。しかし、ESCAPE句はこれには含むことはできません。 状況によっては背後の演算子名を代わりに使わなければならない場合もあります。

Also see the starts-with operator <literal>^@</literal> and the corresponding <function>starts_with()</function> function, which are useful in cases where simply matching the beginning of a string is needed. 単に文字列の先頭からの開始が必要なだけのケースであれば、そこから開始演算子^@とそれに対応するstarts_with関数もあります。

9.7.2. SIMILAR TO正規表現 #

<title><function>SIMILAR TO</function> Regular Expressions</title>
string SIMILAR TO pattern [ESCAPE escape-character]
string NOT SIMILAR TO pattern [ESCAPE escape-character]

The <function>SIMILAR TO</function> operator returns true or false depending on whether its pattern matches the given string. It is similar to <function>LIKE</function>, except that it interprets the pattern using the SQL standard's definition of a regular expression. SQL regular expressions are a curious cross between <function>LIKE</function> notation and common (POSIX) regular expression notation. SIMILAR TO演算子は、そのパターンが与えられた文字列に一致するかどうかにより、真もしくは偽を返します。 これは、標準SQLの正規表現定義を使用してパターンを解釈するという点以外は、LIKEに類似しています。 SQLの正規表現は、LIKE表記と一般的な(POSIX)正規表現の表記とを混ぜ合わせたようなものになっています。

Like <function>LIKE</function>, the <function>SIMILAR TO</function> operator succeeds only if its pattern matches the entire string; this is unlike common regular expression behavior where the pattern can match any part of the string. Also like <function>LIKE</function>, <function>SIMILAR TO</function> uses <literal>_</literal> and <literal>%</literal> as wildcard characters denoting any single character and any string, respectively (these are comparable to <literal>.</literal> and <literal>.*</literal> in POSIX regular expressions). LIKEと同様、SIMILAR TO演算子は、そのパターンが文字列全体に一致した場合のみ真を返します。これは、パターンが文字列の一部分であっても一致する、一般的な正規表現の動作とは異なっています。 また、LIKEと同様、SIMILAR TOでは、%および_を、それぞれ任意の文字列および任意の単一文字を意味するワイルドカード文字として使用します(これらは、POSIX正規表現での.*および.に相当します)。

In addition to these facilities borrowed from <function>LIKE</function>, <function>SIMILAR TO</function> supports these pattern-matching metacharacters borrowed from POSIX regular expressions: LIKEから取り入れた上記の機能に加え、SIMILAR TOでは、以下のようにPOSIX正規表現から取り入れたパターンマッチメタ文字もサポートしています。

  • <literal>|</literal> denotes alternation (either of two alternatives). |は、二者択一(2つの選択肢のうちいずれか)を意味します。

  • <literal>*</literal> denotes repetition of the previous item zero or more times. *は、直前の項目の0回以上の繰り返しを意味します。

  • <literal>+</literal> denotes repetition of the previous item one or more times. +は、直前の項目の1回以上の繰り返しを意味します。

  • <literal>?</literal> denotes repetition of the previous item zero or one time. ?は、直前の項目の0回もしくは1回の繰り返しを意味します。

  • <literal>{</literal><replaceable>m</replaceable><literal>}</literal> denotes repetition of the previous item exactly <replaceable>m</replaceable> times. {m}は、直前の項目の正確なm回の繰り返しを意味します。

  • <literal>{</literal><replaceable>m</replaceable><literal>,}</literal> denotes repetition of the previous item <replaceable>m</replaceable> or more times. {m,}は、直前の項目のm回以上の繰り返しを意味します。

  • <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal> denotes repetition of the previous item at least <replaceable>m</replaceable> and not more than <replaceable>n</replaceable> times. {m,n}は、直前の項目のm回以上かつn回以下の繰り返しを意味します。

  • Parentheses <literal>()</literal> can be used to group items into a single logical item. 丸括弧()は、項目を1つの論理項目にグループ化することができます。

  • A bracket expression <literal>[...]</literal> specifies a character class, just as in POSIX regular expressions. 大括弧式[...]は、POSIX正規表現と同様に文字クラスを指定します。

Notice that the period (<literal>.</literal>) is not a metacharacter for <function>SIMILAR TO</function>. SIMILAR TOではピリオド(.)はメタ文字ではないことに注意してください。

As with <function>LIKE</function>, a backslash disables the special meaning of any of these metacharacters. A different escape character can be specified with <literal>ESCAPE</literal>, or the escape capability can be disabled by writing <literal>ESCAPE ''</literal>. LIKEと同様、バックスラッシュは全てのメタ文字の特殊な意味を無効にします。 異なるエスケープ文字をESCAPEで指定することもできますし、ESCAPE ''と書くことにより、エスケープ機能を無効にすることもできます。

According to the SQL standard, omitting <literal>ESCAPE</literal> means there is no escape character (rather than defaulting to a backslash), and a zero-length <literal>ESCAPE</literal> value is disallowed. <productname>PostgreSQL</productname>'s behavior in this regard is therefore slightly nonstandard. SQL標準によれば、ESCAPEは(デフォルトがバックスラッシュとなるのではなく)エスケープ文字が存在しないことを意味します。長さゼロのESCAPEは使用できません。 ですからこの点でPostgreSQLは少し非標準な振る舞いをします。

Another nonstandard extension is that following the escape character with a letter or digit provides access to the escape sequences defined for POSIX regular expressions; see <xref linkend="posix-character-entry-escapes-table"/>, <xref linkend="posix-class-shorthand-escapes-table"/>, and <xref linkend="posix-constraint-escapes-table"/> below. 他の非標準の拡張としては、エスケープ文字に続く文字あるいは数字を用いてPOSIX正規表現で定義されたエスケープシーケンスへのアクセスを提供するというのがあります。 以下の表 9.20表 9.21表 9.22を参照してください。

Some examples: 例を示します。

'abc' SIMILAR TO 'abc'          true
'abc' SIMILAR TO 'a'            false
'abc' SIMILAR TO '%(b|d)%'      true
'abc' SIMILAR TO '(b|c)%'       false
'-abc-' SIMILAR TO '%\mabc\M%'  true
'xabcy' SIMILAR TO '%\mabc\M%'  false

The <function>substring</function> function with three parameters provides extraction of a substring that matches an SQL regular expression pattern. The function can be written according to standard SQL syntax: 3つのパラメータを持つsubstring関数を使用して、SQL正規表現パターンに一致する部分文字列を取り出すことができます。 標準SQLの構文にしたがって、この関数は次のように書くことができます。

substring(string similar pattern escape escape-character)

or using the now obsolete SQL:1999 syntax: あるいは今では廃れたSQL:1999の構文を使って次のように書くことができます。

substring(string from pattern for escape-character)

or as a plain three-argument function: あるいは単なる3引数関数として次のように書くこともできます。

substring(string, pattern, escape-character)

As with <literal>SIMILAR TO</literal>, the specified pattern must match the entire data string, or else the function fails and returns null. To indicate the part of the pattern for which the matching data sub-string is of interest, the pattern should contain two occurrences of the escape character followed by a double quote (<literal>"</literal>). <!&#45;- " font-lock sanity &#45;-> The text matching the portion of the pattern between these separators is returned when the match is successful. SIMILAR TOと同様、指定したパターンがデータ文字列全体に一致する必要があります。一致しない場合、関数は失敗し、NULLを返します。 マッチするデータのうちの対象とする部分文字列に対応するパターンの部分を示すために、エスケープ文字の後に二重引用符(")を繋げたものを2つパターンに含める必要があります。 " font-lock sanity マッチが成功すると、これらの区切り文字で囲まれたパターンの部分に一致するテキストが返されます。

The escape-double-quote separators actually divide <function>substring</function>'s pattern into three independent regular expressions; for example, a vertical bar (<literal>|</literal>) in any of the three sections affects only that section. Also, the first and third of these regular expressions are defined to match the smallest possible amount of text, not the largest, when there is any ambiguity about how much of the data string matches which pattern. (In POSIX parlance, the first and third regular expressions are forced to be non-greedy.) エスケープ文字と二重引用符による区切りは実際にはsubstringのパターン引数を3つの独立した正規表現に分割します。 たとえば3つのセクションのどこかに置いた垂直線(|)はそのセクションにしか影響を及ぼしません。 また、どのパターンにデータ文字列がマッチするかについて曖昧さがある場合は、最初と3番目の正規表現は、可能な最大のテキストではなく、最小のテキストにマッチするものとして定義されます。 (POSIX用語では、最初と3番目の正規表現は非貪欲(non-greedy)に強制されます。)

As an extension to the SQL standard, <productname>PostgreSQL</productname> allows there to be just one escape-double-quote separator, in which case the third regular expression is taken as empty; or no separators, in which case the first and third regular expressions are taken as empty. SQL標準への拡張として、PostgreSQLは、二重引用符による区切りが一個だけ存在することを許容し、その場合は3番目の正規表現が空として扱われます。 あるいは、二重引用符による区切りがないことも許容し、その場合は最初と3番目の正規表現は空として扱われます。

Some examples, with <literal>#&quot;</literal> delimiting the return string: 例:#"を使用して返される文字列を区切ります。

substring('foobar' similar '%#"o_b#"%' escape '#')   oob
substring('foobar' similar '#"o_b#"%' escape '#')    NULL

9.7.3. POSIX正規表現 #

<title><acronym>POSIX</acronym> Regular Expressions</title>

<xref linkend="functions-posix-table"/> lists the available operators for pattern matching using POSIX regular expressions. 表 9.16に、POSIX正規表現を使ったパターンマッチに使用可能な演算子を列挙します。

表9.16 正規表現マッチ演算子

<title>Regular Expression Match Operators</title>

Operator 演算子

Description 説明

Example(s)

text ~ textboolean

String matches regular expression, case sensitively 文字列が正規表現にマッチ、大文字小文字の区別あり

'thomas' ~ 't.*ma't

text ~* textboolean

String matches regular expression, case-insensitively 文字列が正規表現にマッチ、大文字小文字の区別なし

'thomas' ~* 'T.*ma't

text !~ textboolean

String does not match regular expression, case sensitively 文字列が正規表現にマッチしない、大文字小文字の区別あり

'thomas' !~ 't.*max't

text !~* textboolean

String does not match regular expression, case-insensitively 文字列が正規表現にマッチしない、大文字小文字の区別なし

'thomas' !~* 'T.*ma'f


<acronym>POSIX</acronym> regular expressions provide a more powerful means for pattern matching than the <function>LIKE</function> and <function>SIMILAR TO</function> operators. Many Unix tools such as <command>egrep</command>, <command>sed</command>, or <command>awk</command> use a pattern matching language that is similar to the one described here. POSIX正規表現は、パターンマッチという意味合いでは、LIKEおよびSIMILAR TO演算子よりもさらに強力です。 egrepsed、あるいはawkのような多くのUnixツールはここで解説しているのと類似したパターンマッチ言語を使用しています。

A regular expression is a character sequence that is an abbreviated definition of a set of strings (a <firstterm>regular set</firstterm>). A string is said to match a regular expression if it is a member of the regular set described by the regular expression. As with <function>LIKE</function>, pattern characters match string characters exactly unless they are special characters in the regular expression language &mdash; but regular expressions use different special characters than <function>LIKE</function> does. Unlike <function>LIKE</function> patterns, a regular expression is allowed to match anywhere within a string, unless the regular expression is explicitly anchored to the beginning or end of the string. 正規表現とは文字列の集合(正規集合)の簡略された定義である文字が連なっているものです。 ある文字列が正規表現で記述された正規集合の要素になっていれば、その文字列は正規表現にマッチしていると呼ばれます。 LIKEと同様、正規表現言語で特殊文字とされているもの以外、パターン文字は文字列と完全にマッチされます。とは言っても、正規表現はLIKE関数が使用するのとは異なる特殊文字を使用します。 LIKE関数のパターンと違って正規表現は、明示的に正規表現が文字列の最初または最後からと位置指定されていない限り文字列内のどの位置でもマッチを行えます。

Some examples: 例:

'abcd' ~ 'bc'     true
'abcd' ~ 'a.c'    true — dot matches any character
'abcd' ~ 'a.*d'   true — * repeats the preceding pattern item
'abcd' ~ '(b|x)'  true — | means OR, parentheses group
'abcd' ~ '^a'     true — ^ anchors to start of string
'abcd' ~ '^(b|c)' false — would match except for anchoring

The <acronym>POSIX</acronym> pattern language is described in much greater detail below. POSIXパターン言語について以下により詳しく説明します。

The <function>substring</function> function with two parameters, <function>substring(<replaceable>string</replaceable> from <replaceable>pattern</replaceable>)</function>, provides extraction of a substring that matches a POSIX regular expression pattern. It returns null if there is no match, otherwise the first portion of the text that matched the pattern. But if the pattern contains any parentheses, the portion of the text that matched the first parenthesized subexpression (the one whose left parenthesis comes first) is returned. You can put parentheses around the whole expression if you want to use parentheses within it without triggering this exception. If you need parentheses in the pattern before the subexpression you want to extract, see the non-capturing parentheses described below. 2つのパラメータを持つsubstring関数、substring(string from pattern)を使用して、POSIX正規表現パターンにマッチする部分文字列を取り出すことができます。 この関数は、マッチするものがない場合にはNULLを返し、ある場合はパターンに最初にマッチしたテキストの一部を返します。 しかし、丸括弧を持つパターンの場合、最初の丸括弧内部分正規表現(左丸括弧が最初に来るもの)にマッチするテキストの一部が返されます。 この例外を起こさずにパターン中に丸括弧を使用したいのであれば、常に正規表現全体を丸括弧で囲むことができます。 パターン内の抽出対象の部分文字列より前に丸括弧が必要な場合、後述の捕捉されない丸括弧を参照してください。

Some examples: 例:

substring('foobar' from 'o.b')     oob
substring('foobar' from 'o(.)b')   o

The <function>regexp_count</function> function counts the number of places where a POSIX regular expression pattern matches a string. It has the syntax <function>regexp_count</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>start</replaceable> <optional>, <replaceable>flags</replaceable> </optional></optional>). <replaceable>pattern</replaceable> is searched for in <replaceable>string</replaceable>, normally from the beginning of the string, but if the <replaceable>start</replaceable> parameter is provided then beginning from that character index. The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. For example, including <literal>i</literal> in <replaceable>flags</replaceable> specifies case-insensitive matching. Supported flags are described in <xref linkend="posix-embedded-options-table"/>. regexp_count関数は、POSIX正規表現パターンが文字列とマッチした箇所の数をカウントします。 この関数はregexp_count(string,pattern[,start[,flags]])という構文を持ちます。 patternstringで検索されます。 通常は文字列の先頭から検索されますが、startパラメータが指定されている場合は、その文字インデックスから検索が開始されます。 flagsパラメータは、オプションのテキスト文字列であり、関数の動作を変更する0個以上の単一文字フラグを含みます。 たとえば、flagsiを含めると、大文字と小文字を区別しないマッチングを指定します。 サポートされているフラグは表 9.24で説明されています。

Some examples: 例:

regexp_count('ABCABCAXYaxy', 'A.')          3
regexp_count('ABCABCAXYaxy', 'A.', 1, 'i')  4

The <function>regexp_instr</function> function returns the starting or ending position of the <replaceable>N</replaceable>'th match of a POSIX regular expression pattern to a string, or zero if there is no such match. It has the syntax <function>regexp_instr</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>start</replaceable> <optional>, <replaceable>N</replaceable> <optional>, <replaceable>endoption</replaceable> <optional>, <replaceable>flags</replaceable> <optional>, <replaceable>subexpr</replaceable> </optional></optional></optional></optional></optional>). <replaceable>pattern</replaceable> is searched for in <replaceable>string</replaceable>, normally from the beginning of the string, but if the <replaceable>start</replaceable> parameter is provided then beginning from that character index. If <replaceable>N</replaceable> is specified then the <replaceable>N</replaceable>'th match of the pattern is located, otherwise the first match is located. If the <replaceable>endoption</replaceable> parameter is omitted or specified as zero, the function returns the position of the first character of the match. Otherwise, <replaceable>endoption</replaceable> must be one, and the function returns the position of the character following the match. The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Supported flags are described in <xref linkend="posix-embedded-options-table"/>. For a pattern containing parenthesized subexpressions, <replaceable>subexpr</replaceable> is an integer indicating which subexpression is of interest: the result identifies the position of the substring matching that subexpression. Subexpressions are numbered in the order of their leading parentheses. When <replaceable>subexpr</replaceable> is omitted or zero, the result identifies the position of the whole match regardless of parenthesized subexpressions. regexp_instr関数は、文字列に対するPOSIX正規表現パターンのN番目のマッチの開始位置または終了位置を返します。 マッチがない場合は0を返します。 構文は、regexp_instr(string, pattern [, start [, N [, endoption [, flags [, subexpr ]]]]])を持ちます。 patternstring内で検索されます。通常は文字列の先頭から検索されますが、startパラメータが指定されている場合は、その文字インデックスから検索が開始されます。 Nが指定されている場合は、パターンのN番目の一致が検索されます。 それ以外の場合は、最初の一致が検索されます。 endoptionパラメータが省略されているか0が指定されている場合、関数は一致の最初の文字の位置を返します。 それ以外の場合は、endoptionは1である必要があり、関数は一致の次の文字の位置を返します。 flagsパラメータは、関数の動作を変更する0個以上の単一文字フラグを含むオプションのテキスト文字列です。 サポートされているフラグは表 9.24で説明されています。 カッコで囲まれた部分式を含むパターンでは、subexprは対象の部分式を示す整数です。 結果は、その部分式に一致する部分文字列の位置を示します。 部分式は先頭のカッコの順に番号が付けられます。 subexprが省略されているか0の場合、結果はカッコで囲まれた部分式に関係なく、一致全体の位置を示します。

Some examples: 例を示します。

regexp_instr('number of your street, town zip, FR', '[^,]+', 1, 2)
                                   23
regexp_instr('ABCDEFGHI', '(c..)(...)', 1, 1, 0, 'i', 2)
                                   6

The <function>regexp_like</function> function checks whether a match of a POSIX regular expression pattern occurs within a string, returning boolean true or false. It has the syntax <function>regexp_like</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>flags</replaceable> </optional>). The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Supported flags are described in <xref linkend="posix-embedded-options-table"/>. This function has the same results as the <literal>~</literal> operator if no flags are specified. If only the <literal>i</literal> flag is specified, it has the same results as the <literal>~*</literal> operator. regexp_like関数は、POSIX正規表現パターンの一致が文字列内にあるかどうかをチェックし、ブール値trueまたはfalseを返します。 構文はregexp_likestring,pattern[,flags])です。 flagsパラメータは、関数の動作を変更する0個以上の単一文字フラグを含むオプションのテキスト文字列です。 サポートされているフラグは表 9.24で説明されています。 フラグが指定されていない場合、この関数は~演算子と同じ結果になります。 iフラグのみが指定されている場合、~*演算子と同じ結果になります。

Some examples: 例を示します。

regexp_like('Hello World', 'world')       false
regexp_like('Hello World', 'world', 'i')  true

The <function>regexp_match</function> function returns a text array of matching substring(s) within the first match of a POSIX regular expression pattern to a string. It has the syntax <function>regexp_match</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>flags</replaceable> </optional>). If there is no match, the result is <literal>NULL</literal>. If a match is found, and the <replaceable>pattern</replaceable> contains no parenthesized subexpressions, then the result is a single-element text array containing the substring matching the whole pattern. If a match is found, and the <replaceable>pattern</replaceable> contains parenthesized subexpressions, then the result is a text array whose <replaceable>n</replaceable>'th element is the substring matching the <replaceable>n</replaceable>'th parenthesized subexpression of the <replaceable>pattern</replaceable> (not counting <quote>non-capturing</quote> parentheses; see below for details). The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Supported flags are described in <xref linkend="posix-embedded-options-table"/>. regexp_match関数はPOSIX正規表現パターンを文字列にマッチさせた結果、一致した最初の部分文字列のテキスト配列を返します。 regexp_match(string, pattern [, flags ])の構文になります。 マッチするものがなければ、結果はNULLとなります。 マッチする部分があり、かつpatternが丸括弧で括られた部分文字列を含まない場合、結果はパターン全体にマッチする部分文字列を含む単一要素のテキスト配列となります。 マッチする部分があり、かつpatternが丸括弧で括られた部分文字列を含む場合、結果はテキスト配列で、そのn番目の要素はpatternn番目に丸括弧で括られた部分文字列にマッチする部分文字列となります(捕捉されない丸括弧は数えません。詳細は以下を参照してください)。 flagsパラメータは、関数の動作を変更するゼロもしくは複数の単一文字フラグを含むオプションのテキスト文字列です。 有効なフラグは表 9.24に記載されています。

Some examples: 例:

SELECT regexp_match('foobarbequebaz', 'bar.*que');
 regexp_match
--------------
 {barbeque}
(1 row)

SELECT regexp_match('foobarbequebaz', '(bar)(beque)');
 regexp_match
--------------
 {bar,beque}
(1 row)

ヒント

In the common case where you just want the whole matching substring or <literal>NULL</literal> for no match, the best solution is to use <function>regexp_substr()</function>. However, <function>regexp_substr()</function> only exists in <productname>PostgreSQL</productname> version 15 and up. When working in older versions, you can extract the first element of <function>regexp_match()</function>'s result, for example: 部分文字列全体を一致させたい、またはNULLを一致させたくないという一般的なケースでは、最善の解決策はregexp_substr()を使用することです。 しかし、regexp_substr()PostgreSQLバージョン15以降にしか存在しません。 古いバージョンで作業する場合、以下のようにregexp_match()の結果の最初の要素を抽出することができます。

SELECT (regexp_match('foobarbequebaz', 'bar.*que'))[1];
 regexp_match
--------------
 barbeque
(1 row)

The <function>regexp_matches</function> function returns a set of text arrays of matching substring(s) within matches of a POSIX regular expression pattern to a string. It has the same syntax as <function>regexp_match</function>. This function returns no rows if there is no match, one row if there is a match and the <literal>g</literal> flag is not given, or <replaceable>N</replaceable> rows if there are <replaceable>N</replaceable> matches and the <literal>g</literal> flag is given. Each returned row is a text array containing the whole matched substring or the substrings matching parenthesized subexpressions of the <replaceable>pattern</replaceable>, just as described above for <function>regexp_match</function>. <function>regexp_matches</function> accepts all the flags shown in <xref linkend="posix-embedded-options-table"/>, plus the <literal>g</literal> flag which commands it to return all matches, not just the first one. regexp_matches関数はPOSIX正規表現パターンを文字列にマッチさせた結果、一致した部分文字列のテキスト配列の集合を返します。 構文はregexp_matchと同じです。 この関数は、マッチするものがないときは行を返しませんが、マッチするものがあり、gフラグが指定されていないときは1行だけ、マッチするものがN個あり、gフラグが指定されているときはN行を返します。 返される各行は上でregexp_matchについて説明したのと全く同じで、マッチする部分文字列全体、またはpatternの丸括弧で括られた部分文字列にマッチする部分文字列を含むテキスト配列です。 regexp_matches表 9.24に示すすべてのフラグに加え、最初のマッチだけでなくすべてのマッチを返すgを受け付けます。

Some examples: 例:

SELECT regexp_matches('foo', 'not there');
 regexp_matches
----------------
(0 rows)

SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g');
 regexp_matches
----------------
 {bar,beque}
 {bazil,barf}
(2 rows)

ヒント

In most cases <function>regexp_matches()</function> should be used with the <literal>g</literal> flag, since if you only want the first match, it's easier and more efficient to use <function>regexp_match()</function>. However, <function>regexp_match()</function> only exists in <productname>PostgreSQL</productname> version 10 and up. When working in older versions, a common trick is to place a <function>regexp_matches()</function> call in a sub-select, for example: 最初にマッチするものだけが必要なときはregexp_match()を使う方がより簡単で効率的ですから、regexp_matches()はほとんどの場合gフラグを指定して使われるでしょう。 しかし、regexp_match()PostgreSQLのバージョン10以上でのみ利用できます。 古いバージョンを使う時によくある手法は、以下の例のように、副SELECTの中にregexp_matches()の呼び出しを入れることです。

SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;

This produces a text array if there's a match, or <literal>NULL</literal> if not, the same as <function>regexp_match()</function> would do. Without the sub-select, this query would produce no output at all for table rows without a match, which is typically not the desired behavior. これはregexp_match()と同じく、マッチするものがあればテキスト配列を生成し、マッチしなければNULLとなります。 副SELECTを使わなければ、マッチするものがないテーブル行については問い合わせの出力が生成されず、多くの場合に期待される動作と異なります。

The <function>regexp_replace</function> function provides substitution of new text for substrings that match POSIX regular expression patterns. It has the syntax <function>regexp_replace</function>(<replaceable>source</replaceable>, <replaceable>pattern</replaceable>, <replaceable>replacement</replaceable> <optional>, <replaceable>start</replaceable> <optional>, <replaceable>N</replaceable> </optional></optional> <optional>, <replaceable>flags</replaceable> </optional>). (Notice that <replaceable>N</replaceable> cannot be specified unless <replaceable>start</replaceable> is, but <replaceable>flags</replaceable> can be given in any case.) The <replaceable>source</replaceable> string is returned unchanged if there is no match to the <replaceable>pattern</replaceable>. If there is a match, the <replaceable>source</replaceable> string is returned with the <replaceable>replacement</replaceable> string substituted for the matching substring. The <replaceable>replacement</replaceable> string can contain <literal>\</literal><replaceable>n</replaceable>, where <replaceable>n</replaceable> is 1 through 9, to indicate that the source substring matching the <replaceable>n</replaceable>'th parenthesized subexpression of the pattern should be inserted, and it can contain <literal>\&amp;</literal> to indicate that the substring matching the entire pattern should be inserted. Write <literal>\\</literal> if you need to put a literal backslash in the replacement text. <replaceable>pattern</replaceable> is searched for in <replaceable>string</replaceable>, normally from the beginning of the string, but if the <replaceable>start</replaceable> parameter is provided then beginning from that character index. By default, only the first match of the pattern is replaced. If <replaceable>N</replaceable> is specified and is greater than zero, then the <replaceable>N</replaceable>'th match of the pattern is replaced. If the <literal>g</literal> flag is given, or if <replaceable>N</replaceable> is specified and is zero, then all matches at or after the <replaceable>start</replaceable> position are replaced. (The <literal>g</literal> flag is ignored when <replaceable>N</replaceable> is specified.) The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Supported flags (though not <literal>g</literal>) are described in <xref linkend="posix-embedded-options-table"/>. regexp_replace関数は、POSIX正規表現パターンにマッチする部分文字列を新規テキストと置換します。 構文は、regexp_replace(source, pattern, replacement[, start[, N]][, flags ])です。 (startが指定されない限り、Nを指定できないこと、flagsはいつでも指定できることに注意してください。) patternにマッチしない場合は、source文字列がそのまま返されます。 マッチすると、マッチ部分文字列をreplacement文字列で置換したsource文字列が返されます。 replacement文字列に\nnは1から9までの数字)を入れて、パターン内のn番目の丸括弧つき部分表現にマッチする元の部分文字列を挿入することができます。 また、\&を入れて、パターン全体とマッチする部分文字列を挿入することもできます。 置換テキスト内にバックスラッシュそのものを挿入する必要がある時は\\と記述します。 通常stringの先頭からpatternが文字列内で検索されますが、start引数が与えられるとその文字インデックスから検索されます。 デフォルトではパターンに一致した最初のマッチのみが置き換えられます。 Nが指定され、それがゼロよりも大きい時は、パターンとN番目に一致したマッチが置き換えられます。 gフラグが指定されるか、Nが指定されてそれがゼロなら、start位置あるいはそれ以降のすべてのマッチが置き換えられます。 (gフラグはNが指定されている時は無視されます。) flagsパラメータは、関数の動作を変更するゼロもしくはそれ以上の1文字フラグを含むオプションのテキスト文字列です。 有効なフラグは(gを除く)表 9.24に記述されています。

Some examples: 例:

regexp_replace('foobarbaz', 'b..', 'X')
                                   fooXbaz
regexp_replace('foobarbaz', 'b..', 'X', 'g')
                                   fooXX
regexp_replace('foobarbaz', 'b(..)', 'X\1Y', 'g')
                                   fooXarYXazY
regexp_replace('A PostgreSQL function', 'a|e|i|o|u', 'X', 1, 0, 'i')
                                   X PXstgrXSQL fXnctXXn
regexp_replace('A PostgreSQL function', 'a|e|i|o|u', 'X', 1, 3, 'i')
                                   A PostgrXSQL function

The <function>regexp_split_to_table</function> function splits a string using a POSIX regular expression pattern as a delimiter. It has the syntax <function>regexp_split_to_table</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>flags</replaceable> </optional>). If there is no match to the <replaceable>pattern</replaceable>, the function returns the <replaceable>string</replaceable>. If there is at least one match, for each match it returns the text from the end of the last match (or the beginning of the string) to the beginning of the match. When there are no more matches, it returns the text from the end of the last match to the end of the string. The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. <function>regexp_split_to_table</function> supports the flags described in <xref linkend="posix-embedded-options-table"/>. regexp_split_to_table関数はPOSIX正規表現パターンを区切り文字として使用し、文字列を分割します。regexp_split_to_table(string, pattern [, flags ])の構文になります。 patternにマッチしない場合、関数はstringを返します。 少なくともひとつのマッチがあれば、それぞれのマッチに対して関数は最後のマッチの終わり(あるいは文字列の始め)から最初のマッチまでのテキストを返します。 もはやマッチしなくなると最後のマッチの終わりから文字列の最後までテキストを返します。 flagsパラメータは、関数の動作を変更するゼロもしくは複数の単一文字フラグを含むオプションのテキスト文字列です。 regexp_split_to_table表 9.24で記載されているフラグをサポートします。

The <function>regexp_split_to_array</function> function behaves the same as <function>regexp_split_to_table</function>, except that <function>regexp_split_to_array</function> returns its result as an array of <type>text</type>. It has the syntax <function>regexp_split_to_array</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>flags</replaceable> </optional>). The parameters are the same as for <function>regexp_split_to_table</function>. regexp_split_to_array関数は、regexp_split_to_arrayがその結果をtext配列で返すことを除いて、regexp_split_to_tableと同じ動作をします。 regexp_split_to_array(string, pattern [, flags ])の構文になります。 パラメータはregexp_split_to_tableのものと同じです。

Some examples: 例を示します。

SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', '\s+') AS foo;
  foo
-------
 the
 quick
 brown
 fox
 jumps
 over
 the
 lazy
 dog
(9 rows)

SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', '\s+');
              regexp_split_to_array
-----------------------------------------------
 {the,quick,brown,fox,jumps,over,the,lazy,dog}
(1 row)

SELECT foo FROM regexp_split_to_table('the quick brown fox', '\s*') AS foo;
 foo
-----
 t
 h
 e
 q
 u
 i
 c
 k
 b
 r
 o
 w
 n
 f
 o
 x
(16 rows)

As the last example demonstrates, the regexp split functions ignore zero-length matches that occur at the start or end of the string or immediately after a previous match. This is contrary to the strict definition of regexp matching that is implemented by the other regexp functions, but is usually the most convenient behavior in practice. Other software systems such as Perl use similar definitions. 最後の例が明らかにしているように、regexp分割関数は文字列の最初あるいは終わり、もしくは前のマッチの直後に発生する長さを持たないマッチを無視します。 他の正規表現関数で実装されたregexpマッチの厳格な定義にこれは相容れませんが、実務上は最も使い勝手の良い動作です。 Perlのような他のソフトウェアシステムも似たような定義を使用します。

The <function>regexp_substr</function> function returns the substring that matches a POSIX regular expression pattern, or <literal>NULL</literal> if there is no match. It has the syntax <function>regexp_substr</function>(<replaceable>string</replaceable>, <replaceable>pattern</replaceable> <optional>, <replaceable>start</replaceable> <optional>, <replaceable>N</replaceable> <optional>, <replaceable>flags</replaceable> <optional>, <replaceable>subexpr</replaceable> </optional></optional></optional></optional>). <replaceable>pattern</replaceable> is searched for in <replaceable>string</replaceable>, normally from the beginning of the string, but if the <replaceable>start</replaceable> parameter is provided then beginning from that character index. If <replaceable>N</replaceable> is specified then the <replaceable>N</replaceable>'th match of the pattern is returned, otherwise the first match is returned. The <replaceable>flags</replaceable> parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Supported flags are described in <xref linkend="posix-embedded-options-table"/>. For a pattern containing parenthesized subexpressions, <replaceable>subexpr</replaceable> is an integer indicating which subexpression is of interest: the result is the substring matching that subexpression. Subexpressions are numbered in the order of their leading parentheses. When <replaceable>subexpr</replaceable> is omitted or zero, the result is the whole match regardless of parenthesized subexpressions. regexp_substr関数は、POSIX正規表現パターンと一致する部分文字列を返します。 一致しない場合はNULLを返します。 regexp_substrstring,pattern[,start[,N[,flags[,subexpr]]]])の構文となっています。 patternstring内で検索されます。通常は文字列の先頭から検索されますが、startパラメータが指定されている場合は、その文字インデックスから検索が開始されます。 Nが指定されている場合は、パターンのN番目に一致するものが返されます。 指定されていない場合は、最初に一致するものが返されます。 flagsパラメータは、関数の動作を変更する0個以上の単一文字フラグを含むオプションのテキスト文字列です。 サポートされているフラグは表 9.24で説明されています。 カッコで囲まれた部分式を含むパターンの場合、subexprは対象となる部分式を示す整数です。 結果はその部分式に一致する部分文字列になります。 部分式には、先頭のカッコの順に番号が付けられます。 subexprが省略されているか0の場合、結果はカッコで囲まれた部分式に関係なく全体に一致します。

Some examples: 例:

regexp_substr('number of your street, town zip, FR', '[^,]+', 1, 2)
                                    town zip
regexp_substr('ABCDEFGHI', '(c..)(...)', 1, 1, 'i', 2)
                                   FGH

derived from the re_syntax.n man page

9.7.3.1. 正規表現の詳細 #

<title>Regular Expression Details</title>

<productname>PostgreSQL</productname>'s regular expressions are implemented using a software package written by Henry Spencer. Much of the description of regular expressions below is copied verbatim from his manual. PostgreSQLの正規表現はHenry Spencerにより書かれたソフトウェアパッケージを使用して実装されています。 以下に説明する正規表現の多くの部分は同氏のマニュアルから一字一句複製したものです。

Regular expressions (<acronym>RE</acronym>s), as defined in <acronym>POSIX</acronym> 1003.2, come in two forms: <firstterm>extended</firstterm> <acronym>RE</acronym>s or <acronym>ERE</acronym>s (roughly those of <command>egrep</command>), and <firstterm>basic</firstterm> <acronym>RE</acronym>s or <acronym>BRE</acronym>s (roughly those of <command>ed</command>). <productname>PostgreSQL</productname> supports both forms, and also implements some extensions that are not in the POSIX standard, but have become widely used due to their availability in programming languages such as Perl and Tcl. <acronym>RE</acronym>s using these non-POSIX extensions are called <firstterm>advanced</firstterm> <acronym>RE</acronym>s or <acronym>ARE</acronym>s in this documentation. AREs are almost an exact superset of EREs, but BREs have several notational incompatibilities (as well as being much more limited). We first describe the ARE and ERE forms, noting features that apply only to AREs, and then describe how BREs differ. POSIX 1003.2の定義によると、正規表現(RE)には2つの形式があるとされます。拡張REもしくはERE(大まかにいってegrepに代表されるもの)、および基本REもしくはBRE(大まかにいってedに代表されるもの)です。 PostgreSQLは両方の形式をサポートし、さらに、POSIX標準にはないけれどもPerlやTclなどのプログラミング言語で利用できることから広く使用されるようになった、いくつかの拡張もサポートしています。 本書では、非POSIX拡張を使用したRE高度なREもしくはAREと呼びます。AREはEREの正確な上位セットですが、BREとは複数の記法上の非互換な点があります(さらに非常に多くの制限が課されています)。 まず、AREとERE形式について説明し、そして、AREにのみ適用される機能の注意を、さらにBREとの違いについて説明します。

注記

<productname>PostgreSQL</productname> always initially presumes that a regular expression follows the ARE rules. However, the more limited ERE or BRE rules can be chosen by prepending an <firstterm>embedded option</firstterm> to the RE pattern, as described in <xref linkend="posix-metasyntax"/>. This can be useful for compatibility with applications that expect exactly the <acronym>POSIX</acronym> 1003.2 rules. PostgreSQLは常に、まず正規表現はARE規則に従うと推測します。 しかし、REパターンの前に、9.7.3.4に記載されているような埋め込みオプションを追加することにより、より限られたERE、あるいはBRE規則を選択することができます。 これは、POSIX1003.2の規則を正確に期待しているアプリケーションとの互換性に関して有用です。

A regular expression is defined as one or more <firstterm>branches</firstterm>, separated by <literal>|</literal>. It matches anything that matches one of the branches. 正規表現は|で区切られた、1つまたは複数のブランチとして定義されます。 ブランチのいずれか1つにマッチすればマッチしたことになります。

A branch is zero or more <firstterm>quantified atoms</firstterm> or <firstterm>constraints</firstterm>, concatenated. It matches a match for the first, followed by a match for the second, etc.; an empty branch matches the empty string. ブランチはゼロ個以上の量化アトムもしくは制約の連結です。 最初のものにマッチに、次に第2番目のものにマッチを、というふうにマッチします。なお、空のブランチは空文字列にマッチします。

A quantified atom is an <firstterm>atom</firstterm> possibly followed by a single <firstterm>quantifier</firstterm>. Without a quantifier, it matches a match for the atom. With a quantifier, it can match some number of matches of the atom. An <firstterm>atom</firstterm> can be any of the possibilities shown in <xref linkend="posix-atoms-table"/>. The possible quantifiers and their meanings are shown in <xref linkend="posix-quantifiers-table"/>. 量化アトムとは、単一の量指定子が後ろに付くアトムのことです。 量指定子がないと、アトムにマッチするものがマッチしたことになります。 量指定子がある場合、アトムとのマッチが何回あるかでマッチしたことになります。 アトムは、表 9.17に示したもののいずれかを取ることができます。 表 9.18に設定可能な量指定子とその意味を示します。

A <firstterm>constraint</firstterm> matches an empty string, but matches only when specific conditions are met. A constraint can be used where an atom could be used, except it cannot be followed by a quantifier. The simple constraints are shown in <xref linkend="posix-constraints-table"/>; some more constraints are described later. 制約は空文字に、特定の条件に合う場合のみにマッチします。 アトムを使用できるところには制約を使用することができます。ただしその後に量指定子を付けることはできません。 単純な制約を表 9.19に示します。後で他のいくつかの制約を説明します。

表9.17 正規表現のアトム

<title>Regular Expression Atoms</title>
アトム説明
(re) (ここでre は任意の正規表現で、)reとのマッチに適合するもです。 マッチは可能である報告用と意味づけられます。
(?:re) 上と同じ。ただし、マッチは報告用と意味づけられません。(捕捉されない括弧の集合)(AREのみ)
. 任意の1文字にマッチします。
[chars] ブラケット式charsのいずれか1つにマッチします (詳細は9.7.3.2を参照してください)。
\k (ここでkは英数字以外です。)普通の文字として指定した文字にマッチします。例えば、\\はバックスラッシュ文字です。
\c ここでcは英数字です (おそらく他の文字が後に続きます)。 エスケープです。 9.7.3.3を参照してください (AREのみ、EREとBREではこれはcにマッチします)。
{ 直後に数字以外がある場合、左中括弧{にマッチします。 直後に数字が続く場合、bound(後述)の始まりです。
x ここでxは他に意味を持たない1文字です。 xにマッチします。

An RE cannot end with a backslash (<literal>\</literal>). REはバックスラッシュ\を終端とすることはできません。

注記

If you have <xref linkend="guc-standard-conforming-strings"/> turned off, any backslashes you write in literal string constants will need to be doubled. See <xref linkend="sql-syntax-strings"/> for more information. もしstandard_conforming_stringsパラメータをoffにしていた場合、リテラル文字列定数に記述するバックスラッシュは2倍必要となります。 詳細は4.1.2.1を参照してください。

表9.18 正規表現量指定子

<title>Regular Expression Quantifiers</title>
量指定子マッチ
* アトムの0個以上複数の並びにマッチ
+ アトムの1個以上複数の並びにマッチ
? アトムの0個または1個の並びにマッチ
{m} アトムの正確にm個の並びにマッチ
{m,} アトムのm個以上の並びにマッチ
{m,n} アトムのm個以上n以下の並びにマッチ。 mnを超えることはできません。
*? *の最短マッチを行うバージョン
+? +の最短マッチを行うバージョン
?? ?の最短マッチを行うバージョン
{m}? {m}の最短マッチを行うバージョン
{m,}? {m,}の最短マッチを行うバージョン
{m,n}? {m,n}の最短マッチを行うバージョン

The forms using <literal>{</literal><replaceable>...</replaceable><literal>}</literal> are known as <firstterm>bounds</firstterm>. The numbers <replaceable>m</replaceable> and <replaceable>n</replaceable> within a bound are unsigned decimal integers with permissible values from 0 to 255 inclusive. {...}を使用する形式はバウンドとして知られています。 バウンド内のmnという数は符号なし10進整数であり、0以上255以下の値を取ることができます。

<firstterm>Non-greedy</firstterm> quantifiers (available in AREs only) match the same possibilities as their corresponding normal (<firstterm>greedy</firstterm>) counterparts, but prefer the smallest number rather than the largest number of matches. See <xref linkend="posix-matching-rules"/> for more detail. 最短マッチを行う量指定子(AREのみで使用可能)は、対応する通常の(欲張りの)ものと同じものにマッチしますが、最大のマッチではなく最小のマッチを取ります。 詳細は9.7.3.5を参照してください。

注記

A quantifier cannot immediately follow another quantifier, e.g., <literal>**</literal> is invalid. A quantifier cannot begin an expression or subexpression or follow <literal>^</literal> or <literal>|</literal>. 量指定子の直後に量指定子を続けることはできません。例えば**は無効です。 量指定子から式や副式を始めることはできず、また、^|の直後に付けることもできません。

表9.19 正規表現制約

<title>Regular Expression Constraints</title>
制約説明
^ 文字列の先頭にマッチ
$ 文字列の末尾にマッチ
(?=re) 先行肯定検索は、reにマッチする部分文字列が始まる任意の場所にマッチします(AREのみ)。
(?!re) 先行否定検索は、reにマッチしない部分文字列が始まる任意の場所にマッチします(AREのみ)。
(?<=re) 後方肯定検索reにマッチする部分文字列が終わる任意の場所にマッチします(AREのみ)。
(?<!re) 後方否定検索reにマッチしない部分文字列が終わる任意の場所にマッチします(AREのみ)。

Lookahead and lookbehind constraints cannot contain <firstterm>back references</firstterm> (see <xref linkend="posix-escape-sequences"/>), and all parentheses within them are considered non-capturing. 先行検索制約および後方検索制約には後方参照9.7.3.3を参照)を含めることはできません。また、その中の括弧は全て取り込むものではないとみなされます。

9.7.3.2. ブラケット式 #

<title>Bracket Expressions</title>

A <firstterm>bracket expression</firstterm> is a list of characters enclosed in <literal>[]</literal>. It normally matches any single character from the list (but see below). If the list begins with <literal>^</literal>, it matches any single character <emphasis>not</emphasis> from the rest of the list. If two characters in the list are separated by <literal>-</literal>, this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, e.g., <literal>[0-9]</literal> in <acronym>ASCII</acronym> matches any decimal digit. It is illegal for two ranges to share an endpoint, e.g., <literal>a-c-e</literal>. Ranges are very collating-sequence-dependent, so portable programs should avoid relying on them. ブラケット式とは、[]内の文字のリストです。 通常これはそのリスト内の任意の1文字にマッチします(しかし、以降を参照してください)。 リストが^から始まる場合、そのリストの残りにはない任意の1文字にマッチします。 リスト内の2文字が-で区切られていた場合、これは2つ(を含む)の間にある文字範囲全体を表す省略形となります。例えば、ASCIIにおける[0-9]は全ての数字にマッチします。 例えばa-c-eといった、終端を共有する2つの範囲は不正です。 範囲は並びの照合順に非常に依存しています。ですので、移植予定のプログラムではこれに依存してはなりません。

To include a literal <literal>]</literal> in the list, make it the first character (after <literal>^</literal>, if that is used). To include a literal <literal>-</literal>, make it the first or last character, or the second endpoint of a range. To use a literal <literal>-</literal> as the first endpoint of a range, enclose it in <literal>[.</literal> and <literal>.]</literal> to make it a collating element (see below). With the exception of these characters, some combinations using <literal>[</literal> (see next paragraphs), and escapes (AREs only), all other special characters lose their special significance within a bracket expression. In particular, <literal>\</literal> is not special when following ERE or BRE rules, though it is special (as introducing an escape) in AREs. このリストに]そのものを含めるには、それを先頭文字(もしそれが使用されれば^の後)にしてください。 -そのものを含めるには、それを先頭もしくは末尾の文字とするか、範囲の2番目の終端としてください。 -を範囲の最初の終端で使用するには、[..]でそれを囲み、照合要素(後述)にしてください。 これら文字と、[(次段落を参照)のなんらかの組み合わせ、およびエスケープ(AREのみ)を例外として、他の全ての特殊文字はブラケット式内では特殊な意味を持ちません。 特に、\はEREとBRE規則に従う場合は特別でなくなります。しかし、AREでは(エスケープの始まりとして)特別な意味を持ちます。

Within a bracket expression, a collating element (a character, a multiple-character sequence that collates as if it were a single character, or a collating-sequence name for either) enclosed in <literal>[.</literal> and <literal>.]</literal> stands for the sequence of characters of that collating element. The sequence is treated as a single element of the bracket expression's list. This allows a bracket expression containing a multiple-character collating element to match more than one character, e.g., if the collating sequence includes a <literal>ch</literal> collating element, then the RE <literal>[[.ch.]]*c</literal> matches the first five characters of <literal>chchcc</literal>. ブラケット式内に、照合要素(文字、単一文字であるかのように照合する複数文字の並び、もしくはそれぞれの照合並びの名前)が[..]の間にあると、その照合要素の文字の並びを意味します。 この並びはブラケット式のリストの一要素として取り扱われます。 このことにより、ブラケット式は要素を照合する複数文字を含むブラケット式を1文字以上にマッチさせることができます。例えば、照合並びがch照合要素を含む場合、正規表現[[.ch.]]*cchchccという文字の最初の5文字にマッチします。

注記

<productname>PostgreSQL</productname> currently does not support multi-character collating elements. This information describes possible future behavior. 今のところ、PostgreSQLは複数文字照合要素をサポートしません。 この情報は将来の振舞いの可能性を説明したものです。

Within a bracket expression, a collating element enclosed in <literal>[=</literal> and <literal>=]</literal> is an <firstterm>equivalence class</firstterm>, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were <literal>[.</literal> and <literal>.]</literal>.) For example, if <literal>o</literal> and <literal>^</literal> are the members of an equivalence class, then <literal>[[=o=]]</literal>, <literal>[[=^=]]</literal>, and <literal>[o^]</literal> are all synonymous. An equivalence class cannot be an endpoint of a range. ブラケット式内の[==]の間に照合要素は同値クラスです。全ての照合要素の文字の並びが自身を含むものと等価であることを示します。 (他に等価な照合要素がある場合、[..]で囲まれたかのように扱われます。) 例えば、[[=o=]][[=^=]]および[o^]が全て同意語であれば、o^は同値クラスのメンバです。 同値クラスは範囲の終端にはなりません。

Within a bracket expression, the name of a character class enclosed in <literal>[:</literal> and <literal>:]</literal> stands for the list of all characters belonging to that class. A character class cannot be used as an endpoint of a range. The <acronym>POSIX</acronym> standard defines these character class names: <literal>alnum</literal> (letters and numeric digits), <literal>alpha</literal> (letters), <literal>blank</literal> (space and tab), <literal>cntrl</literal> (control characters), <literal>digit</literal> (numeric digits), <literal>graph</literal> (printable characters except space), <literal>lower</literal> (lower-case letters), <literal>print</literal> (printable characters including space), <literal>punct</literal> (punctuation), <literal>space</literal> (any white space), <literal>upper</literal> (upper-case letters), and <literal>xdigit</literal> (hexadecimal digits). The behavior of these standard character classes is generally consistent across platforms for characters in the 7-bit ASCII set. Whether a given non-ASCII character is considered to belong to one of these classes depends on the <firstterm>collation</firstterm> that is used for the regular-expression function or operator (see <xref linkend="collation"/>), or by default on the database's <envar>LC_CTYPE</envar> locale setting (see <xref linkend="locale"/>). The classification of non-ASCII characters can vary across platforms even in similarly-named locales. (But the <literal>C</literal> locale never considers any non-ASCII characters to belong to any of these classes.) In addition to these standard character classes, <productname>PostgreSQL</productname> defines the <literal>word</literal> character class, which is the same as <literal>alnum</literal> plus the underscore (<literal>_</literal>) character, and the <literal>ascii</literal> character class, which contains exactly the 7-bit ASCII set. ブラケット式内では、[::]の間にある文字クラスの名称は、そのクラスに属する全ての文字のリストを意味します。 文字クラスは範囲の終端位置としては使用できません。 POSIX標準は以下の文字クラス名を定義しています。 alnum(文字と数字)、alpha(文字)、blank(空白とタブ)、cntrl(制御文字)、digit(数字)、graph(空白以外の印字可能文字)、lower(小文字)、print(空白を含む印字可能文字)、punct(句読点)、space(空白)、upper(大文字)、xdigit(16進数)です。 これらの標準文字クラスの振る舞いは7-bit ASCII集合の範囲であれば一般にどのプラットフォームでも同じです。 与えられた非ASCII文字がこれらの文字クラスに属すると考えられるかどうかは、正規表現関数または演算子(24.2参照)で使用される照合順、あるいはデフォルトとしてはデータベースのLC_CTYPEロケール(24.1)の設定によります。 非ASCII文字の分類は、たとえ似たような名前のロケールであってもプラットフォームによって異なることがありえます。 (ただしCロケールでは、すべての非ASCII文字はこれらのクラスのどれにも所属しないものとされます。) これらの標準クラスに加え、PostgreSQLではalnumと同様だがアンダースコア(_)文字を加えたword文字クラス、そして7-bit ASCII集合を正確に含むascii文字クラスが定義されています。

There are two special cases of bracket expressions: the bracket expressions <literal>[[:&lt;:]]</literal> and <literal>[[:&gt;:]]</literal> are constraints, matching empty strings at the beginning and end of a word respectively. A word is defined as a sequence of word characters that is neither preceded nor followed by word characters. A word character is any character belonging to the <literal>word</literal> character class, that is, any letter, digit, or underscore. This is an extension, compatible with but not specified by <acronym>POSIX</acronym> 1003.2, and should be used with caution in software intended to be portable to other systems. The constraint escapes described below are usually preferable; they are no more standard, but are easier to type. ブラケット式には2つの特殊な場合があります。[[:<:]][[:>:]]というブラケット式は、先頭と終端の単語がそれぞれ空文字であることにマッチする制約です。 単語は、単語文字が前後に付かない単語文字の並びとして定義されます。 単語文字とはword文字クラスに所属するすべての文字、すなわちすべての文字、数字、アンダースコアです。 これは、POSIX 1003.2との互換性はありますが、そこでは定義されていない式です。ですので、他システムへ移植予定のソフトウェアでの使用には注意が必要です。 通常後述の制約エスケープの方がよく使われます。これはもはや標準ではありませんが、入力しやすいものです。

9.7.3.3. 正規表現エスケープ #

<title>Regular Expression Escapes</title>

<firstterm>Escapes</firstterm> are special sequences beginning with <literal>\</literal> followed by an alphanumeric character. Escapes come in several varieties: character entry, class shorthands, constraint escapes, and back references. A <literal>\</literal> followed by an alphanumeric character but not constituting a valid escape is illegal in AREs. In EREs, there are no escapes: outside a bracket expression, a <literal>\</literal> followed by an alphanumeric character merely stands for that character as an ordinary character, and inside a bracket expression, <literal>\</literal> is an ordinary character. (The latter is the one actual incompatibility between EREs and AREs.) エスケープとは、\から始まり英数字がその後に続く特殊な並びです。 エスケープには、文字エントリ、クラス省略、制約エスケープ、後方参照といった様々な変種があります。 \の後に英数字が続くけれども、有効なエスケープを構成しない並びはAREでは不正です。 EREにはエスケープはありません。ブラケット式の外側では、\の後に英数字が続く並びは単に普通の文字としてその文字を意味します。ブラケット式の内側では、\は普通の文字です。 (後者はEREとARE間の非互換性の1つです。)

<firstterm>Character-entry escapes</firstterm> exist to make it easier to specify non-printing and other inconvenient characters in REs. They are shown in <xref linkend="posix-character-entry-escapes-table"/>. 文字エントリエスケープは非印字文字やRE内でその他の不便な文字の指定を簡略化するために存在します。 これらを表 9.20に示します。

<firstterm>Class-shorthand escapes</firstterm> provide shorthands for certain commonly-used character classes. They are shown in <xref linkend="posix-class-shorthand-escapes-table"/>. クラス省略エスケープは、あるよく使用される文字クラスの省略形を提供します。 これらを表 9.21に示します。

A <firstterm>constraint escape</firstterm> is a constraint, matching the empty string if specific conditions are met, written as an escape. They are shown in <xref linkend="posix-constraint-escapes-table"/>. 制約エスケープは、指定した条件に合う場合に空文字にマッチする制約をエスケープとして表したものです。 これらを表 9.22に示します。

A <firstterm>back reference</firstterm> (<literal>\</literal><replaceable>n</replaceable>) matches the same string matched by the previous parenthesized subexpression specified by the number <replaceable>n</replaceable> (see <xref linkend="posix-constraint-backref-table"/>). For example, <literal>([bc])\1</literal> matches <literal>bb</literal> or <literal>cc</literal> but not <literal>bc</literal> or <literal>cb</literal>. The subexpression must entirely precede the back reference in the RE. Subexpressions are numbered in the order of their leading parentheses. Non-capturing parentheses do not define subexpressions. The back reference considers only the string characters matched by the referenced subexpression, not any constraints contained in it. For example, <literal>(^\d)\1</literal> will match <literal>22</literal>. 後方参照\n)は、直前に括弧で囲まれた副式によってマッチされた、n番目の同一文字列にマッチします(表 9.23を参照してください)。 例えば、([bc])\1bbもしくはccにマッチしますが、bccbにはマッチしません。REでは副式全体は後方参照の前になければなりません。 副式は開括弧の順番で番号付けされます。 取り込まない括弧は副式を定義しません。 後方参照は参照される副式にマッチした文字列のみを考慮し、そこに含まれる制約は考慮しません。 たとえば、(^\d)\122にマッチします。

表9.20 正規表現文字エントリエスケープ

<title>Regular Expression Character-Entry Escapes</title>
エスケープ説明
\a C言語と同じ警報(ベル)文字
\b C言語と同じバックスペース
\B バックスラッシュの必要な二重化回数を減らすためのバックスラッシュ(\)の同義語
\cX (ここでXは任意の文字で)その下位5ビットがXと同一、その他のビットが0となる文字
\e 照合順名がESCとなる文字、それに失敗したら、033という8進数値を持つ文字。
\f C言語と同じ改ページ
\n C言語と同じ改行
\r C言語と同じ復帰
\t C言語と同じ水平タブ
\uwxyz (ここでwxyzは正確に4桁の16進数で)その16進数での値が0xwxyzという文字
\Ustuvwxyz (ここでstuvwxyzは正確に8桁の16進数で)その16進数での値が0xstuvwxyzという文字
\v C言語と同じ垂直タブ
\xhhh (ここでhhhは任意の16進数の並びで)その文字の16進数値が0xhhhとなる文字(使用される16進数の桁数にかかわらず単一の文字)
\0 その値が0(NULLバイト)となる文字
\xy (ここでxyは正確に2桁の8進数で、後方参照ではない)その値が0xyとなる文字
\xyz (ここでxyzは正確に3桁の8進数で、後方参照ではない)その値が0xyzとなる文字

Hexadecimal digits are <literal>0</literal>-<literal>9</literal>, <literal>a</literal>-<literal>f</literal>, and <literal>A</literal>-<literal>F</literal>. Octal digits are <literal>0</literal>-<literal>7</literal>. 16進数の桁とは0-9a-fA-Fです。 8進数の桁とは0-7です。

Numeric character-entry escapes specifying values outside the ASCII range (0&ndash;127) have meanings dependent on the database encoding. When the encoding is UTF-8, escape values are equivalent to Unicode code points, for example <literal>\u1234</literal> means the character <literal>U+1234</literal>. For other multibyte encodings, character-entry escapes usually just specify the concatenation of the byte values for the character. If the escape value does not correspond to any legal character in the database encoding, no error will be raised, but it will never match any data. ASCIIの範囲(0-127)外の値を指定した数字のエントリエスケープは、その意味がデータベースエンコーディングに依存します。 エンコーディングがUTF-8の場合、エスケープ値はユニコード符号位置に相当します。例えば、\u1234は文字U+1234を意味します。 その他のマルチバイトエンコーディングでは、文字エントリエスケープはたいてい文字のバイト値の連結を指定します。 エスケープ値がデータベースエンコーディングでのいかなる正当な文字にも対応しない場合、エラーは起こりませんが、いかなるデータにもマッチしません。

The character-entry escapes are always taken as ordinary characters. For example, <literal>\135</literal> is <literal>]</literal> in ASCII, but <literal>\135</literal> does not terminate a bracket expression. この文字エントリエスケープは常に普通の文字と解釈されます。 例えば、\135はASCIIの]となり、\135はブラケット式の終端にはなりません。

表9.21 正規表現クラス省略エスケープ

<title>Regular Expression Class-Shorthand Escapes</title>
エスケープ説明
\d [[:digit:]]のようなすべての数字にマッチします。
\s [[:space:]]のようなすべての空白文字にマッチします。
\w [[:word:]]のようなすべての単語文字にマッチします。
\D [^[:digit:]]のようなすべての非数字にマッチします。
\S [^[:space:]]のようなすべての非空白文字にマッチします。
\W [^[:word:]]のようなすべての非単語文字にマッチします。

The class-shorthand escapes also work within bracket expressions, although the definitions shown above are not quite syntactically valid in that context. For example, <literal>[a-c\d]</literal> is equivalent to <literal>[a-c[:digit:]]</literal>. クラス省略エスケープはブラケット式の中でも使えますが、上に示した定義はそのコンテキストでは構文的に正しいとは言えません。 たとえば[a-c\d][a-c[:digit:]]と同様です。

表9.22 正規表現制約エスケープ

<title>Regular Expression Constraint Escapes</title>
エスケープ説明
\A 文字列の先頭にのみマッチします(^との違いについては9.7.3.5を参照してください)。
\m 単語の先頭にのみマッチします。
\M 単語の末尾にのみマッチします。
\y 単語の先頭もしくは末尾にのみマッチします。
\Y 単語の先頭もしくは末尾以外の場所にのみマッチします。
\Z 文字列の末尾にのみマッチします($との違いについては9.7.3.5を参照してください)。

A word is defined as in the specification of <literal>[[:&lt;:]]</literal> and <literal>[[:&gt;:]]</literal> above. Constraint escapes are illegal within bracket expressions. 単語は前述の[[:<:]][[:>:]]の規定通りに定義されます。ブラケット式内では制約エスケープは不正です。

表9.23 正規表現後方参照

<title>Regular Expression Back References</title>
エスケープ説明
\m (ここでmは非ゼロの数です。)副式のm番目への後方参照
\mnn (ここでmは非ゼロの数です。nnでさらに桁を指定します。mnn10進数値は取り込み括弧の数よりも多くてはなりません。)副式のmnn番目への後方参照

注記

There is an inherent ambiguity between octal character-entry escapes and back references, which is resolved by the following heuristics, as hinted at above. A leading zero always indicates an octal escape. A single non-zero digit, not followed by another digit, is always taken as a back reference. A multi-digit sequence not starting with a zero is taken as a back reference if it comes after a suitable subexpression (i.e., the number is in the legal range for a back reference), and otherwise is taken as octal. 8進数の文字エントリエスケープと後方参照の間には曖昧性があります。上でヒントとして示したようにこれは以下の発見的手法で解決されます。 先頭の0は常に8進数エスケープを示します。 その後に数字が続かない単一の非ゼロ数字は常に後方参照として解釈されます。 ゼロから始まらない複数数字の並びは、適切な副式の後にあれば(つまり、その番号が後方参照用の範囲内にあれば)後方参照として解釈されます。さもなくば、8進数として解釈されます。

9.7.3.4. 正規表現メタ構文 #

<title>Regular Expression Metasyntax</title>

In addition to the main syntax described above, there are some special forms and miscellaneous syntactic facilities available. 上述の主構文の他に、特殊な形式や雑多な構文的な機能が使用可能です。

An RE can begin with one of two special <firstterm>director</firstterm> prefixes. If an RE begins with <literal>***:</literal>, the rest of the RE is taken as an ARE. (This normally has no effect in <productname>PostgreSQL</productname>, since REs are assumed to be AREs; but it does have an effect if ERE or BRE mode had been specified by the <replaceable>flags</replaceable> parameter to a regex function.) If an RE begins with <literal>***=</literal>, the rest of the RE is taken to be a literal string, with all characters considered ordinary characters. REは、2つの特殊な決定子前置詞のどちらかから始まります。 REが***:から始まるものであれば、REの残りはAREと解釈されます。 (PostgreSQLはREをAREとして推測するため、通常は影響を受けません。ただし、正規表現関数に対してflagsパラメータを指定されたEREやBREモードでは影響を受けます。) REが***=から始まるものであれば、REの残りは、全ての文字を普通の文字とみなしたリテラル文字列と解釈されます。

An ARE can begin with <firstterm>embedded options</firstterm>: a sequence <literal>(?</literal><replaceable>xyz</replaceable><literal>)</literal> (where <replaceable>xyz</replaceable> is one or more alphabetic characters) specifies options affecting the rest of the RE. These options override any previously determined options &mdash; in particular, they can override the case-sensitivity behavior implied by a regex operator, or the <replaceable>flags</replaceable> parameter to a regex function. The available option letters are shown in <xref linkend="posix-embedded-options-table"/>. Note that these same option letters are used in the <replaceable>flags</replaceable> parameters of regex functions. AREは埋め込みオプションから始められます。(?xyz)という並びで残りのREに影響するオプションを指定します(ここでxyzは1つ以上の英字です)。 このオプションは、事前に決定されたオプションを上書きします。— 特に、正規表現演算子、もしくは正規表現関数に与えられたflagsパラメータにより示される大文字小文字の区別を上書きします。 使用可能なオプション文字を表 9.24に示します。 これらの同じオプション文字が、正規表現関数のflagsパラメータで使用されることに注意して下さい。

表9.24 ARE埋め込みオプション文字

<title>ARE Embedded-Option Letters</title>
オプション説明
b 残りのREはBRE
c 大文字小文字を区別するマッチ(演算子で規定される大文字小文字の区別よりこの指定が優先されます)。
e 残りのREはERE
i 大文字小文字を区別しないマッチ(9.7.3.5を参照)(演算子で規定される大文字小文字の区別よりこの指定が優先されます)。
m nの歴史的な同義語
n 改行を区別するマッチ(9.7.3.5を参照)
p 部分的な改行を区別するマッチ(9.7.3.5を参照)
q 残りのREはリテラル(引用符付けされた)文字列、全て普通の文字
s 改行を区別しないマッチ(デフォルト)
t 厳しめの構文(デフォルト、後述)
w 部分的な改行区別の逆(ワイアード)マッチ(9.7.3.5を参照)
x 拡張構文(後述)

Embedded options take effect at the <literal>)</literal> terminating the sequence. They can appear only at the start of an ARE (after the <literal>***:</literal> director if any). 埋め込みオプションはその並びの終端)で有効になります。 AREの先頭(もし***:決定子があればその後)でのみ利用可能です。

In addition to the usual (<firstterm>tight</firstterm>) RE syntax, in which all characters are significant, there is an <firstterm>expanded</firstterm> syntax, available by specifying the embedded <literal>x</literal> option. In the expanded syntax, white-space characters in the RE are ignored, as are all characters between a <literal>#</literal> and the following newline (or the end of the RE). This permits paragraphing and commenting a complex RE. There are three exceptions to that basic rule: 全ての文字が意味を持つ、通常の(厳しめの)RE構文に加え、x埋め込みオプションを指定することで利用できる拡張構文があります。 拡張構文では、RE内の空白文字は無視され、#とその後の改行(もしくはREの終端)の間の全ての文字も同様です。 これにより、段落付けや複雑なREのコメント付けが可能になります。 基本規則に対して3つの例外があります。

  • a white-space character or <literal>#</literal> preceded by <literal>\</literal> is retained 直前に\が付いた空白文字もしくは#は保持されます。

  • white space or <literal>#</literal> within a bracket expression is retained ブラケット式内の空白文字もしくは#は保持されます。

  • white space and comments cannot appear within multi-character symbols, such as <literal>(?:</literal> (?:などの複数文字シンボルでは、空白文字とコメントは不正です。

For this purpose, white-space characters are blank, tab, newline, and any character that belongs to the <replaceable>space</replaceable> character class. ここでの空白文字とは、空白、タブ、改行、スペース文字クラスに属する文字です。

Finally, in an ARE, outside bracket expressions, the sequence <literal>(?#</literal><replaceable>ttt</replaceable><literal>)</literal> (where <replaceable>ttt</replaceable> is any text not containing a <literal>)</literal>) is a comment, completely ignored. Again, this is not allowed between the characters of multi-character symbols, like <literal>(?:</literal>. Such comments are more a historical artifact than a useful facility, and their use is deprecated; use the expanded syntax instead. 最後に、AREのブラケット式の外側では、(?#ttt)という並びはコメントになります(ここでtttを含まない任意のテキストです)。 繰り返しになりますが、これは(?:などの複数文字シンボルの文字間では使用できません。 こうしたコメントは実用性というより歴史的所産です。そのため、この使用は勧めません。代わりに拡張構文を使用してください。

<emphasis>None</emphasis> of these metasyntax extensions is available if an initial <literal>***=</literal> director has specified that the user's input be treated as a literal string rather than as an RE. 初めに***=決定子が指定され、ユーザの入力がREではなくリテラルとして扱われる場合、これらのメタ構文拡張は使用できません

9.7.3.5. 正規表現マッチ規則 #

<title>Regular Expression Matching Rules</title>

In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in the string. If the RE could match more than one substring starting at that point, either the longest possible match or the shortest possible match will be taken, depending on whether the RE is <firstterm>greedy</firstterm> or <firstterm>non-greedy</firstterm>. REが文字列の中の1つ以上の部分文字列とマッチする場合において、REは最初にマッチが始まった部分文字列とマッチします。 その位置からまた1つ以上の部分文字列とマッチした際は、正規表現は最短マッチを行わない(欲張り型)最短マッチを行う(非欲張り型)かによって、最長マッチもしくは最短マッチの文字列のどちらかにマッチします

Whether an RE is greedy or not is determined by the following rules: REが最長マッチかどうかは以下の規則によって決まります。

  • Most atoms, and all constraints, have no greediness attribute (because they cannot match variable amounts of text anyway). ほとんどのアトムおよび全ての式は欲張り属性を持ちません(これらは変動する量のテキストにまったくマッチしないからです)。

  • Adding parentheses around an RE does not change its greediness. REを括弧で括ることは欲張りかどうかを変更しません。

  • A quantified atom with a fixed-repetition quantifier (<literal>{</literal><replaceable>m</replaceable><literal>}</literal> or <literal>{</literal><replaceable>m</replaceable><literal>}?</literal>) has the same greediness (possibly none) as the atom itself. {m}もしくは{m}?といった固定繰り返し数の量指定子を持つ量指定付きアトムは、アトム自身と同一の欲張りさを持ちます(まったく持たない可能性もあります)。

  • A quantified atom with other normal quantifiers (including <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}</literal> with <replaceable>m</replaceable> equal to <replaceable>n</replaceable>) is greedy (prefers longest match). 他の通常の量指定子({m,n}mnが等しい場合も含みます)を持つ量指定付きアトムは欲張り型です(最長マッチを使用します)。

  • A quantified atom with a non-greedy quantifier (including <literal>{</literal><replaceable>m</replaceable><literal>,</literal><replaceable>n</replaceable><literal>}?</literal> with <replaceable>m</replaceable> equal to <replaceable>n</replaceable>) is non-greedy (prefers shortest match). 他の非欲張り型量指定子({m,n}?mnが等しい場合も含みます)を持つ量指定付きアトムは非欲張り型です(最短マッチを使用します)。

  • A branch &mdash; that is, an RE that has no top-level <literal>|</literal> operator &mdash; has the same greediness as the first quantified atom in it that has a greediness attribute. 最上位レベルの|演算子を持たないREであるブランチは、最初の欲張り属性を持つ量指定付きアトムと同一の欲張り属性を持ちます。

  • An RE consisting of two or more branches connected by the <literal>|</literal> operator is always greedy. |演算子で接続された2つ以上のブランチからなるREは常に欲張り型です。

The above rules associate greediness attributes not only with individual quantified atoms, but with branches and entire REs that contain quantified atoms. What that means is that the matching is done in such a way that the branch, or whole RE, matches the longest or shortest possible substring <emphasis>as a whole</emphasis>. Once the length of the entire match is determined, the part of it that matches any particular subexpression is determined on the basis of the greediness attribute of that subexpression, with subexpressions starting earlier in the RE taking priority over ones starting later. 上の規則は、個々の量指定付きアトムだけではなく、量指定付きアトムを複数含むブランチやRE全体の欲張り属性に関連します。 つまり、ブランチやRE全体が全体として最長または最短の部分文字列にマッチするという方法でマッチ処理が行われます。 全体のマッチの長さが決まると、特定の部分式にマッチする部分がその部分式の欲張り属性によって決まります。この時、RE内でより前にある部分式が後にある部分式よりも高い優先度を持ちます。

An example of what this means: この意味の例を示します。

SELECT SUBSTRING('XY1234Z', 'Y*([0-9]{1,3})');
Result: 123
SELECT SUBSTRING('XY1234Z', 'Y*?([0-9]{1,3})');
Result: 1

In the first case, the RE as a whole is greedy because <literal>Y*</literal> is greedy. It can match beginning at the <literal>Y</literal>, and it matches the longest possible string starting there, i.e., <literal>Y123</literal>. The output is the parenthesized part of that, or <literal>123</literal>. In the second case, the RE as a whole is non-greedy because <literal>Y*?</literal> is non-greedy. It can match beginning at the <literal>Y</literal>, and it matches the shortest possible string starting there, i.e., <literal>Y1</literal>. The subexpression <literal>[0-9]{1,3}</literal> is greedy but it cannot change the decision as to the overall match length; so it is forced to match just <literal>1</literal>. 最初の例では、Y*が欲張り型であるため、REは全体として欲張り型です。 マッチはYの位置から始まり、そこから可能な限り最長の文字列にマッチします。つまりY123となります。 出力は括弧で括られた部分、つまり123となります。 2番目の例では、Y*?が非欲張り型のため、REは全体として非欲張り型です。 マッチはYの位置から始まり、そこから可能な限り最短の文字列にマッチします。つまりY1となります。 部分式[0-9]{1,3}は欲張り型ですが、決定されたマッチする全体の長さを変更することはできません。したがって、強制的に1にマッチすることになります。

In short, when an RE contains both greedy and non-greedy subexpressions, the total match length is either as long as possible or as short as possible, according to the attribute assigned to the whole RE. The attributes assigned to the subexpressions only affect how much of that match they are allowed to <quote>eat</quote> relative to each other. まとめると、REが欲張り型部分式と非欲張り型部分式の両方を持つ場合、全体のマッチ長はRE全体に割り当てられる属性に応じて、最長マッチ長か最短マッチ長のどちらかになります。 部分式に割り当てられた属性は、部分式の中でどれだけの量をその部分式の中で消費できるかのみに影響します。

The quantifiers <literal>{1,1}</literal> and <literal>{1,1}?</literal> can be used to force greediness or non-greediness, respectively, on a subexpression or a whole RE. This is useful when you need the whole RE to have a greediness attribute different from what's deduced from its elements. As an example, suppose that we are trying to separate a string containing some digits into the digits and the parts before and after them. We might try to do that like this: {1,1}および{1,1}?量指定子を副式もしくはRE全体に使用して、それぞれ、欲張りか欲張りでないかを強制することが可能です。 RE全体に対してはその要素から推論されるものと異なる欲張りさの属性が必要な場合に、これは便利です。 例として、数字をいくつか含む文字列を数字とその前後の部分に分けようとしているとします。 次のようにしてみるかもしれません。

SELECT regexp_match('abc01234xyz', '(.*)(\d+)(.*)');
Result: {abc0123,4,xyz}

That didn't work: the first <literal>.*</literal> is greedy so it <quote>eats</quote> as much as it can, leaving the <literal>\d+</literal> to match at the last possible place, the last digit. We might try to fix that by making it non-greedy: 上手くいきませんでした。最初の.*が欲張りで、可能なだけ消費してしまい、\d+は最後の可能な場所で最後の数字にマッチします。 欲張りでなくすることで直そうとするかもしれません。

SELECT regexp_match('abc01234xyz', '(.*?)(\d+)(.*)');
Result: {abc,0,""}

That didn't work either, because now the RE as a whole is non-greedy and so it ends the overall match as soon as possible. We can get what we want by forcing the RE as a whole to be greedy: またもや上手くいきませんでした。今度は、REが全体として欲張りでなくなってしまい、できる限り早く全体に渡るマッチを終わらせてしまうからです。 RE全体として欲張りにすることで欲しいものが得られます。

SELECT regexp_match('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
Result: {abc,01234,xyz}

Controlling the RE's overall greediness separately from its components' greediness allows great flexibility in handling variable-length patterns. REの全体に渡る欲張りさをその要素の欲張りさと別に制御すれば、可変長のパターンを非常に柔軟に扱えます。

When deciding what is a longer or shorter match, match lengths are measured in characters, not collating elements. An empty string is considered longer than no match at all. For example: <literal>bb*</literal> matches the three middle characters of <literal>abbbc</literal>; <literal>(week|wee)(night|knights)</literal> matches all ten characters of <literal>weeknights</literal>; when <literal>(.*).*</literal> is matched against <literal>abc</literal> the parenthesized subexpression matches all three characters; and when <literal>(a*)*</literal> is matched against <literal>bc</literal> both the whole RE and the parenthesized subexpression match an empty string. マッチが長いか短いかを判断する時には、マッチの長さは照合要素ではなく文字列で測られます。 空文字列はまったくマッチする要素がない文字列よりも長いと考えられます。 例えば、bb*abbbcの真中の3文字とマッチし、(week|wee)(night|knights)weeknightsの全ての10文字とマッチし、abcに対して(.*).*がマッチされると、括弧内の部分正規表現は3つの文字全てにマッチし、bcに対して(a*)*がマッチされると、全体のREと括弧内の正規表現は空文字列にマッチします。

If case-independent matching is specified, the effect is much as if all case distinctions had vanished from the alphabet. When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, e.g., <literal>x</literal> becomes <literal>[xX]</literal>. When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, e.g., <literal>[x]</literal> becomes <literal>[xX]</literal> and <literal>[^x]</literal> becomes <literal>[^xX]</literal>. もし大文字小文字を区別しないマッチが指定されると、アルファベット文字の大文字小文字の区別がまったくなくなったのと同じ効果を与えます。 ブラケット式の外側にアルファベットの大文字小文字が混ざった通常の文字が出てきた場合、例えば、x[xX]となるように大文字小文字ともにブラケット式に実質的に転換されます。 ブラケット式の中に現れた時は、(例えば)[x][xX]となり、また[^x][^xX]となるように、全ての大文字小文字それぞれの対がブラケット式に追加されます。

If newline-sensitive matching is specified, <literal>.</literal> and bracket expressions using <literal>^</literal> will never match the newline character (so that matches will not cross lines unless the RE explicitly includes a newline) and <literal>^</literal> and <literal>$</literal> will match the empty string after and before a newline respectively, in addition to matching at beginning and end of string respectively. But the ARE escapes <literal>\A</literal> and <literal>\Z</literal> continue to match beginning or end of string <emphasis>only</emphasis>. Also, the character class shorthands <literal>\D</literal> and <literal>\W</literal> will match a newline regardless of this mode. (Before <productname>PostgreSQL</productname> 14, they did not match newlines when in newline-sensitive mode. Write <literal>[^[:digit:]]</literal> or <literal>[^[:word:]]</literal> to get the old behavior.) 改行を区別するマッチが指定されると、.^を使用するブラケット式は(REが明示的に改行を含まない限りマッチが行をまたがらないようにするために)改行文字にマッチしなくなります。また、^$はそれぞれ改行直後と直前の空文字列にマッチし、さらに、それぞれ文字列の先頭と末尾にマッチします。 しかし、AREエスケープの\A\Zは、継続して、文字列の先頭と末尾のみにマッチします。 また、文字クラス短縮形\D\Wこのモードが何であれ改行にマッチします。 (PostgreSQL 14より前では、改行敏感モードのときはこれらは改行にマッチしませんでした。 古い挙動で動かすには[^[:digit:]]あるいは[^[:word:]]と書いてください。)

If partial newline-sensitive matching is specified, this affects <literal>.</literal> and bracket expressions as with newline-sensitive matching, but not <literal>^</literal> and <literal>$</literal>. 部分的に改行を区別するマッチが指定されると、.とブラケット式は改行を区別するマッチを行うようになりますが、^$は変更されません。

If inverse partial newline-sensitive matching is specified, this affects <literal>^</literal> and <literal>$</literal> as with newline-sensitive matching, but not <literal>.</literal> and bracket expressions. This isn't very useful but is provided for symmetry. 部分的に改行を区別する逆マッチが指定されると、^$は改行を区別するマッチを行うようになりますが、.とブラケット式は変更されません。 これはあまり有用ではありません。対称性のために提供されています。

9.7.3.6. 制限と互換性 #

<title>Limits and Compatibility</title>

No particular limit is imposed on the length of REs in this implementation. However, programs intended to be highly portable should not employ REs longer than 256 bytes, as a POSIX-compliant implementation can refuse to accept such REs. 本実装ではREの長さに関する制限はありません。 しかし、移植性を高めたいプログラムでは、256バイトを超えるREを使用すべきではありません。POSIX互換の実装ではそうしたREでは混乱する可能性があります。

The only feature of AREs that is actually incompatible with POSIX EREs is that <literal>\</literal> does not lose its special significance inside bracket expressions. All other ARE features use syntax which is illegal or has undefined or unspecified effects in POSIX EREs; the <literal>***</literal> syntax of directors likewise is outside the POSIX syntax for both BREs and EREs. AREの機能のうち、POSIX EREと実質的な非互換性があるのは、\がブラケット式の内側で特殊な意味を失わないという点のみです。 他の全てのARE機能は、POSIX EREでは不正、未定義、未指定な効果となる構文を使用しています。決定子の***構文などはBREおよびEREのPOSIX構文にはありません。

Many of the ARE extensions are borrowed from Perl, but some have been changed to clean them up, and a few Perl extensions are not present. Incompatibilities of note include <literal>\b</literal>, <literal>\B</literal>, the lack of special treatment for a trailing newline, the addition of complemented bracket expressions to the things affected by newline-sensitive matching, the restrictions on parentheses and back references in lookahead/lookbehind constraints, and the longest/shortest-match (rather than first-match) matching semantics. 多くのARE拡張はPerlから拝借したものです。 しかし、いくつかは整理され、Perlの拡張のいくつかは存在しません。 注意すべき非互換性には、\b\B、改行の取り扱いに関する特殊な措置の欠落、改行を区別するマッチに影響する点について補足したブラケット式の追加、括弧と先行・後方検索制約内の後方参照についての制限、最長/最短(最初にマッチするではなく)マッチのセマンティクスがあります。

9.7.3.7. 基本正規表現 #

<title>Basic Regular Expressions</title>

BREs differ from EREs in several respects. In BREs, <literal>|</literal>, <literal>+</literal>, and <literal>?</literal> are ordinary characters and there is no equivalent for their functionality. The delimiters for bounds are <literal>\{</literal> and <literal>\}</literal>, with <literal>{</literal> and <literal>}</literal> by themselves ordinary characters. The parentheses for nested subexpressions are <literal>\(</literal> and <literal>\)</literal>, with <literal>(</literal> and <literal>)</literal> by themselves ordinary characters. <literal>^</literal> is an ordinary character except at the beginning of the RE or the beginning of a parenthesized subexpression, <literal>$</literal> is an ordinary character except at the end of the RE or the end of a parenthesized subexpression, and <literal>*</literal> is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading <literal>^</literal>). Finally, single-digit back references are available, and <literal>\&lt;</literal> and <literal>\&gt;</literal> are synonyms for <literal>[[:&lt;:]]</literal> and <literal>[[:&gt;:]]</literal> respectively; no other escapes are available in BREs. BREはEREといくつかの面において異なります。 BREにおいては、|+?は普通の文字であり、それらの機能と等価なものはありません。 バウンドの区切りは\{\}であり、{}自身は普通の文字です。 副式を入れ子にするための括弧は\(\)であり、()自身は普通の文字です。 ^は、REの先頭にある場合や括弧内の副式の先頭の場合を除き、普通の文字です。 $は、REの末尾にある場合や括弧内の副式の末尾の場合を除き、普通の文字です。 また、*はREの先頭にある場合や括弧内の副式の先頭にある場合には普通の文字になります(その前に^が付いている可能性もあります)。 最後に、1桁の後方参照を使用することができ、また、BREにおいては、\<\>はそれぞれ[[:<:]][[:>:]]と同義です。

end re_syntax.n man page

9.7.3.8. 標準SQLおよびXQueryとの違い #

<title>Differences from SQL Standard and XQuery</title>

Since SQL:2008, the SQL standard includes regular expression operators and functions that performs pattern matching according to the XQuery regular expression standard: SQL:2008以降、標準SQLには正規表現演算子と、XQuery正規表現標準に従ってパターンマッチングを実行する関数が含まれています。

  • LIKE_REGEX

  • OCCURRENCES_REGEX

  • POSITION_REGEX

  • SUBSTRING_REGEX

  • TRANSLATE_REGEX

<productname>PostgreSQL</productname> does not currently implement these operators and functions. You can get approximately equivalent functionality in each case as shown in <xref linkend="functions-regexp-sql-table"/>. (Various optional clauses on both sides have been omitted in this table.) PostgreSQLは現在これらの演算子や関数を実装していません。 表 9.25に示すように、それぞれの場合でほぼ同等の機能を得ることができます(この表では両側のさまざまなオプション句を省略しています)。

表9.25 同等の正規表現関数

<title>Regular Expression Functions Equivalencies</title>
標準SQLPostgreSQL
string LIKE_REGEX patternregexp_like(string, pattern) or string ~ pattern
OCCURRENCES_REGEX(pattern IN string)regexp_count(string, pattern)
POSITION_REGEX(pattern IN string)regexp_instr(string, pattern)
SUBSTRING_REGEX(pattern IN string)regexp_substr(string, pattern)
TRANSLATE_REGEX(pattern IN string WITH replacement)regexp_replace(string, pattern, replacement)

Regular expression functions similar to those provided by PostgreSQL are also available in a number of other SQL implementations, whereas the SQL-standard functions are not as widely implemented. Some of the details of the regular expression syntax will likely differ in each implementation. PostgreSQLで提供されているものと同様の正規表現関数は、他の多くのSQL実装でも利用できますが、標準SQL関数はそれほど広く実装されていません。 正規表現構文の詳細のいくつかは、実装によって異なる可能性があります。

The SQL-standard operators and functions use XQuery regular expressions, which are quite close to the ARE syntax described above. Notable differences between the existing POSIX-based regular-expression feature and XQuery regular expressions include: 標準SQLの演算子と関数は、上で述べたARE構文に極めて近いXQuery正規表現を使用しています。 既存のPOSIXベースの正規表現機能とXQueryの正規表現の主な違いには以下のものが含まれます。

  • XQuery character class subtraction is not supported. An example of this feature is using the following to match only English consonants: <literal>[a-z-[aeiou]]</literal>. XQueryの文字クラス減算はサポートされていません。 この機能の例としては、[a-z-[aeiou]]のようにして英語の子音のみにマッチさせるというのがあります。

  • XQuery character class shorthands <literal>\c</literal>, <literal>\C</literal>, <literal>\i</literal>, and <literal>\I</literal> are not supported. XQueryの文字クラス短縮形\c\C\i\Iはサポートされていません。

  • XQuery character class elements using <literal>\p{UnicodeProperty}</literal> or the inverse <literal>\P{UnicodeProperty}</literal> are not supported. \p{UnicodeProperty}あるいはその逆である\P{UnicodeProperty}を使ったXQueryの文字クラス要素はサポートされていません。

  • POSIX interprets character classes such as <literal>\w</literal> (see <xref linkend="posix-class-shorthand-escapes-table"/>) according to the prevailing locale (which you can control by attaching a <literal>COLLATE</literal> clause to the operator or function). XQuery specifies these classes by reference to Unicode character properties, so equivalent behavior is obtained only with a locale that follows the Unicode rules. POSIXは有効なロケール(演算子あるいは関数のCOLLATE節で制御できます)にしたがい、\w表 9.21参照)のような文字クラスを解釈します。 XQueryはこれらのクラスをUnicodeの文字属性を参照してこれらのクラスを決定します。 ですからUnicodeルールに従うロケールを使用してのみ同等の振る舞いを得ることができます。

  • The SQL standard (not XQuery itself) attempts to cater for more variants of <quote>newline</quote> than POSIX does. The newline-sensitive matching options described above consider only ASCII NL (<literal>\n</literal>) to be a newline, but SQL would have us treat CR (<literal>\r</literal>), CRLF (<literal>\r\n</literal>) (a Windows-style newline), and some Unicode-only characters like LINE SEPARATOR (U+2028) as newlines as well. Notably, <literal>.</literal> and <literal>\s</literal> should count <literal>\r\n</literal> as one character not two according to SQL. SQL標準(XQuery自身ではなく)はPOSIXが提供するより多様なnewlineの亜種を提供しようとしています。 上で述べた改行に敏感なマッチオプションはASCII NL(\n)だけを改行として考慮します。 しかしSQLはCR (\r)、CRLF (\r\n)(Windowsスタイルの改行)、LINE SEPARATOR (U+2028)のようなUnicodeのみの文字も改行として扱うことを求めています。 とりわけ、SQLにおいては、.\s\r\nを2文字ではなく、1文字として数える必要があります。

  • Of the character-entry escapes described in <xref linkend="posix-character-entry-escapes-table"/>, XQuery supports only <literal>\n</literal>, <literal>\r</literal>, and <literal>\t</literal>. 表 9.20で示す文字エントリエスケープのうち、XQueryは\n\r\tだけをサポートしています。

  • XQuery does not support the <literal>[:<replaceable>name</replaceable>:]</literal> syntax for character classes within bracket expressions. XQueryはブラケット式内の文字クラスとして[:name:]構文をサポートしていません。

  • XQuery does not have lookahead or lookbehind constraints, nor any of the constraint escapes described in <xref linkend="posix-constraint-escapes-table"/>. XQueryには先行検索制約および後方検索制約がありませんし、表 9.22に記述された制約エスケープもありません。

  • The metasyntax forms described in <xref linkend="posix-metasyntax"/> do not exist in XQuery. 9.7.3.4に記述されたメタ構文形式はXQueryには存在しません。

  • The regular expression flag letters defined by XQuery are related to but not the same as the option letters for POSIX (<xref linkend="posix-embedded-options-table"/>). While the <literal>i</literal> and <literal>q</literal> options behave the same, others do not: XQueryで定義された正規表現フラグ文字はPOSIX(表 9.24)のオプション文字に関連していますが、同じではありません。 iqオプションは同じように振る舞いますが、その他は違います。

    • XQuery's <literal>s</literal> (allow dot to match newline) and <literal>m</literal> (allow <literal>^</literal> and <literal>$</literal> to match at newlines) flags provide access to the same behaviors as POSIX's <literal>n</literal>, <literal>p</literal> and <literal>w</literal> flags, but they do <emphasis>not</emphasis> match the behavior of POSIX's <literal>s</literal> and <literal>m</literal> flags. Note in particular that dot-matches-newline is the default behavior in POSIX but not XQuery. XQueryのs(ピリオドが改行にマッチすることを許容する)とm^$が改行位置でマッチすることを許容する)フラグは、POSIXのnpwフラグと同じ挙動を提供しますが、POSIXのsmフラグの挙動とは一致しません。 ピリオドが改行にマッチするのはPOSIXではデフォルトの挙動ですが、XQueryではそうでないことに留意してください。

    • XQuery's <literal>x</literal> (ignore whitespace in pattern) flag is noticeably different from POSIX's expanded-mode flag. POSIX's <literal>x</literal> flag also allows <literal>#</literal> to begin a comment in the pattern, and POSIX will not ignore a whitespace character after a backslash. XQueryのx(パターン中の空白を無視する)フラグはPOSIXの拡張モードフラグとは著しく異なります。 POSIXのxフラグは#でパターン中のコメントを始めることもできます。 POSIXはバックスラッシュ以降の空白文字を無視しません。