aboutsummaryrefslogtreecommitdiff
path: root/files/ja/web/javascript/reference/global_objects/regexp/index.html
blob: 8fc458ebfaf08812251e775441a20f4dfc5c7ec0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
---
title: RegExp
slug: Web/JavaScript/Reference/Global_Objects/RegExp
tags:
  - Constructor
  - JavaScript
  - Reference
  - RegExp
  - Regular Expressions
  - コンストラクター
  - 正規表現
translation_of: Web/JavaScript/Reference/Global_Objects/RegExp
---
<div>{{JSRef}}</div>

<p><strong><code>RegExp</code></strong> オブジェクトは、パターンでテキストを検索するために使用します。</p>

<p>正規表現を詳しく知りたい方は <a href="/ja/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript ガイド</a><a href="/ja/docs/Web/JavaScript/Guide/Regular_Expressions">正規表現</a> を参考にしてください。</p>

<h2 id="Description" name="Description">解説</h2>

<h3 id="Literal_notation_and_constructor" name="Literal_notation_and_constructor">リテラル記法とコンストラクター</h3>

<p><code>RegExp</code> オブジェクトを生成するには二通りの方法があります。<em>リテラル記法</em><em>コンストラクター</em>です。</p>

<ul>
 <li><strong>リテラル記法</strong>は引数をスラッシュで囲み、引用符は使用しません。</li>
 <li><strong>コンストラクター関数</strong>の引数はスラッシュで囲むのではなく、引用符を使用します。</li>
</ul>

<p>以下の三つの式は、同じ正規表現を生成します。</p>

<pre class="brush: js notranslate">/ab+c/i
new RegExp(/ab+c/, 'i') // リテラル記法
new RegExp('ab+c', 'i') // コンストラクター
</pre>

<p>リテラル記法では、正規表現が評価されるときにコンパイルを行います。正規表現が変化しない場合は、リテラル記法を使用してください。例えばループ内で使用する正規表現を生成するためにリテラル記法を使用すると、反復処理のたびに正規表現を再コンパイルすることはありません。</p>

<p><code>new RegExp('ab+c')</code> といった正規表現オブジェクトのコンストラクターは、実行時に正規表現をコンパイルします。正規表現パターンが変わることがわかっている場合や、パターンが不明でありユーザー入力など別のソースからパターンを取得する場合は、コンストラクター関数を使用してください。</p>

<h3 id="Flags_in_constructor" name="Flags_in_constructor">コンストラクターのフラグ</h3>

<p>ECMAScript 6 より、第 1 引数が <code>RegExp</code> で第 2 引数に <code><var>flags</var></code> を指定する場合 (<code>new RegExp(/ab+c/, 'i')</code>) に {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") が発生しません。代わりに、引数を元に新たな <code>RegExp</code> が生成されます。</p>

<p>コンストラクター関数を使用する場合は、通常の文字エスケープ規則 (文字列内に特殊文字が含まれるとき、前に <code>\</code> を付加する) が必須です。</p>

<p>例えば、以下 2 つの構文は同等です。</p>

<pre class="brush: js notranslate">let re = /\w+/
let re = new RegExp('\\w+')
</pre>

<h3 id="Perl-like_RegExp_properties" name="Perl-like_RegExp_properties">Perl 風の RegExp プロパティ</h3>

<p>{{JSxRef("RegExp")}} のプロパティのいくつかは、長い名前と短い (Perl 風の) 名前があります。 Both names always refer to the same value. (Perl is the programming language from which JavaScript modeled its regular expressions.). See also <a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#RegExp_Properties">deprecated <code>RegExp</code> properties.</a></p>

<h2 id="Constructor" name="Constructor">コンストラクター</h2>

<dl>
 <dt>{{jsxref("RegExp/RegExp", "RegExp()")}}</dt>
 <dd>新しい <code>RegExp</code> オブジェクトを生成します。</dd>
</dl>

<h2 id="Static_properties" name="Static_properties">静的プロパティ</h2>

<dl>
 <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt>
 <dd>派生オブジェクトを生成するために使用されるコンストラクター関数です。</dd>
 <dt>{{jsxref("RegExp.lastIndex")}}</dt>
 <dd>次のマッチングを開始する位置です。</dd>
</dl>

<h2 id="Instance_properties" name="Instance_properties">インスタンスプロパティ</h2>

<dl>
 <dt>{{JSxRef("RegExp.prototype.flags")}}</dt>
 <dd><code>RegExp</code> オブジェクトのフラグから成る文字列です。</dd>
 <dt>{{JSxRef("RegExp.prototype.dotAll")}}</dt>
 <dd><code>.</code> が改行文字にマッチするかどうか。</dd>
 <dt>{{JSxRef("RegExp.prototype.global")}}</dt>
 <dd>対象文字列で可能なすべてのマッチに対して正規表現をテストするか、それとも、最初のマッチに対してのみテストするどうかのフラグです。</dd>
 <dt>{{JSxRef("RegExp.prototype.ignoreCase")}}</dt>
 <dd>文字列でのマッチを適用する際に、大文字と小文字の違いを無視するかどうかのフラグです。</dd>
 <dt>{{JSxRef("RegExp.prototype.multiline")}}</dt>
 <dd>複数行に渡って文字列を検索するかどうかのフラグです。</dd>
 <dt>{{JSxRef("RegExp.prototype.source")}}</dt>
 <dd>パターンのテキストです。</dd>
 <dt>{{JSxRef("RegExp.prototype.sticky")}}</dt>
 <dd>検索が<ruby>先頭固定<rp> (</rp><rt>sticky</rt><rp>) </rp></ruby>であるかどうかのフラグです。</dd>
 <dt>{{JSxRef("RegExp.prototype.unicode")}}</dt>
 <dd>Unicode 機能が有効かどうかのフラグです。</dd>
</dl>

<h2 id="Instance_methods" name="Instance_methods">インスタンスメソッド</h2>

<dl>
 <dt>{{JSxRef("RegExp.prototype.compile()")}}</dt>
 <dd>スクリプトの実行中に正規表現を (再) コンパイルします。</dd>
 <dt>{{JSxRef("RegExp.prototype.exec()")}}</dt>
 <dd>その文字列のパラメータでのマッチのための検索を実行します。</dd>
 <dt>{{JSxRef("RegExp.prototype.test()")}}</dt>
 <dd>その文字列のパラメータでのマッチのためのテストをします。</dd>
 <dt>{{JSxRef("RegExp.prototype.toString()")}}</dt>
 <dd>特定のオブジェクトを表す文字列を返します。{{JSxRef("Object.prototype.toString()")}} メソッドを上書きします。</dd>
 <dt>{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}</dt>
 <dd>与えられた文字列とのマッチを行い、マッチ結果を返します。</dd>
 <dt>{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}</dt>
 <dd>文字列に対して正規表現で一致したものをすべて返します。</dd>
 <dt>{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}</dt>
 <dd>与えられた文字列のマッチを新しい部分文字列で置き換えます。</dd>
 <dt>{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}</dt>
 <dd>与えられた文字列でマッチを検索し、文字列で見つかったパターンのインデックスを返します。</dd>
 <dt>{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}</dt>
 <dd>文字列を部分文字列に分割し、指定された文字列を配列に分割します。</dd>
</dl>

<h2 id="Examples" name="Examples"></h2>

<h3 id="Using_a_regular_expression_to_change_data_format" name="Using_a_regular_expression_to_change_data_format">正規表現を使用したデータ形式の変更</h3>

<p>以下のスクリプトは、{{jsxref("Global_Objects/String", "String")}} インスタンスの {{jsxref("String.prototype.replace()", "replace()")}} メソッドを使用して、 <em>first last</em> 形式のフォーマットでの名前にマッチさせ、<em>last, first</em> 形式のフォーマットで出力しています。</p>

<p>置換テキスト中で、そのスクリプトは、<code>$1</code><code>$2</code> を使用して、それぞれ対応する正規表現パターンでマッチする括弧がキャプチャした結果を指定しています。</p>

<pre class="brush: js notranslate">let re = /(\w+)\s(\w+)/
let str = 'John Smith'
let newstr = str.replace(re, '$2, $1')
console.log(newstr)
</pre>

<p>これは、 <code>"Smith, John"</code> と表示します。</p>

<h3 id="Using_regular_expression_to_split_lines_with_different_line_endingsends_of_lineline_breaks" name="Using_regular_expression_to_split_lines_with_different_line_endingsends_of_lineline_breaks">正規表現を使用したさまざまな行末/行の終端/改行での行の分割</h3>

<p>既定の行末文字は、プラットフォーム (Unix、Windows など) によって異なります。この例で実行する行分割は、あらゆるプラットフォームで動作します。</p>

<pre class="brush: js notranslate">let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
let lines = text.split(/\r\n|\r|\n/)
console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
</pre>

<p>正規表現内のパターンの順序が重要であることに注意してください。</p>

<h3 id="Using_regular_expression_on_multiple_lines" name="Using_regular_expression_on_multiple_lines">複数行で正規表現を使用する</h3>

<pre class="brush: js notranslate">let s = 'Please yes\nmake my day!'

s.match(/yes.*day/);
// null

s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]
</pre>

<h3 id="Using_a_regular_expression_with_the_sticky_flag" name="Using_a_regular_expression_with_the_sticky_flag">sticky フラグ付きの正規表現の使用</h3>

<p>{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}} フラグは、対象文字列で {{jsxref("RegExp.prototype.lastIndex")}} からマッチングを試みることにより、正規表現の sticky マッチングを実行することを示します。</p>

<pre class="brush: js notranslate">let str = '#foo#'
let regex = /foo/y

regex.lastIndex = 1
regex.test(str)      // true
regex.lastIndex = 5
regex.test(str)      // false (lastIndex is taken into account with sticky flag)
regex.lastIndex      // 0 (reset after match failure)</pre>

<h3 id="The_difference_between_the_sticky_flag_and_the_global_flag" name="The_difference_between_the_sticky_flag_and_the_global_flag">sticky フラグと global フラグの違い</h3>

<p>sticky フラグ <code>y</code> を付けると、次の一致は <code>lastIndex</code> の位置で行われるのに対し、グローバルフラグ <code>g</code> を付けると、検索は <code>lastIndex</code> の位置から始められます。</p>

<pre class="brush: js notranslate">re = /\d/y;
while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);

// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
//   ... and no more match.</pre>

<p>グローバルフラグ <code>g</code> を付けると、3桁だけでなく、6桁すべてが一致します。</p>

<h3 id="Regular_expression_and_Unicode_characters" name="Regular_expression_and_Unicode_characters">正規表現と Unicode 文字</h3>

<p>上の表にもある通り、<code>\w</code><code>\W</code> は ASCII 基本文字にのみマッチします。具体的には <code>a</code> から <code>z</code><code>A</code> から <code>Z</code><code>0</code> から <code>9</code> および <code>_</code> です。</p>

<p>キリル語やヘブライ語で使われるような非 ASCII 文字にマッチさせるには <code>\u<var>hhhh</var></code> 形式 (<code><var>hhhh</var></code> の部分は 16進表記の Unicode 値) を使ってください。</p>

<p>この例は、文字列全体から Unicode 文字列だけを抜き出す方法を示しています。</p>

<pre class="brush: js notranslate">let text = 'Образец text на русском языке'
let regex = /[\u0400-\u04FF]+/g

let match = regex.exec(text)
console.log(match[0])        // logs 'Образец'
console.log(regex.lastIndex) // logs '7'

let match2 = regex.exec(text)
console.log(match2[0])       // logs 'на' [did not log 'text']
console.log(regex.lastIndex) // logs '15'

// and so on
</pre>

<p><a href="/ja/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes">Unicode プロパティエスケープ</a>機能は <code>\p{scx=Cyrl}</code> のように単純な表記を可能にする解決策を導入しています。スクリプト別の完全な Unicode コードブロック (範囲) を知ることができる外部リソースも、 <a href="http://kourge.net/projects/regexp-unicode-block">Regexp-Unicode-block</a> などがあります。</p>

<h3 id="Extracting_sub-domain_name_from_URL" name="Extracting_sub-domain_name_from_URL">URL からのサブドメイン名の抽出</h3>

<pre class="brush: js notranslate">let url = 'http://xxx.domain.com'
console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
</pre>

<h2 id="Specifications" name="Specifications">仕様書</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">仕様書</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2>

<div>
<p>{{Compat("javascript.builtins.RegExp")}}</p>
</div>

<h3 id="Firefox-specific_notes" name="Firefox-specific_notes">Firefox 固有の注意事項</h3>

<p>Firefox 34 より、量指定子を伴うキャプチャグループが動作を妨げている場合に、キャプチャグループにマッチしたテキストが空文字列ではなく <code>undefined</code> になります:</p>

<pre class="brush: js notranslate">// Firefox 33 以前
'x'.replace(/x(.)?/g, function(m, group) {
  console.log("'group:" + group + "'");
});
// 'group:'

// Firefox 34 以降
'x'.replace(/x(.)?/g, function(m, group) {
  console.log("'group:" + group + "'");
});
// 'group:undefined'
</pre>

<p>ウェブの互換性のため <code>RegExp.<var>$N</var></code> は引き続き、 <code>undefined</code> ではなく空文字列を返します (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1053944">bug 1053944</a>)。</p>

<h2 id="See_also" name="See_also">関連情報</h2>

<ul>
 <li><a href="/ja/docs/Web/JavaScript/Guide">JavaScript ガイド</a>内の<a href="/ja/docs/Web/JavaScript/Guide/Regular_Expressions">正規表現</a>の章</li>
 <li>{{jsxref("String.prototype.match()")}}</li>
 <li>{{jsxref("String.prototype.replace()")}}</li>
</ul>