文字列の先頭や末尾などの位置にマッチするパターンを記述する

正規表現では文字列の先頭や末尾、単語の境界など文字そのものではなく位置にマッチするメタ文字が用意されています。例えば文字の先頭とマッチするメタ文字を使用すれば、そのあとに記述したパターンが文字の先頭から始まっている場合だけマッチさせることができます。ここでは JavaScript の正規表現で文字列の先頭や末尾など位置にマッチするパターンの記述方法について解説します。

(Last modified: )

文字列の先頭にマッチする(^)

メタ文字のひとつであるキャレット(^)は文字列の先頭位置ににマッチします。

^

例えば次のようなパターンは文字列の先頭から始まる文字列で、 R で始まり、そのあとに e そして d が続く文字列にマッチします。

const regexp = /^Red/;

Red や Reduce にはマッチします。ただし 文字列の先頭以外にある場合は Red であってもマッチしません。

Red Color
〇 Reduce
✕ Radio
✕ Color is Red
サンプルコード

簡単なサンプルで試してみます。

let regexp = /^Red/;

console.log(regexp.test('Red Table'));
>> true
console.log(regexp.test('Reduce speed'));
>> true
console.log(regexp.test('Border Color is Red'));
>> false

文字列の末尾にマッチする($)

メタ文字のひとつであるドル記号($)は文字列の末尾位置にマッチします。

$

例えば次のようなパターンは Script という文字列が文字列の末尾にある場合にマッチします。

const regexp = /Script$/;

JavaScript や TypeScript にはマッチします。ただし 文字列の末尾以外にある場合は JavaScript であってもマッチしません。

〇 JavaScript
〇 I am studying TypeScript
✕ script
✕ PostScript is difficult
サンプルコード

簡単なサンプルで試してみます。

let regexp = /Script$/;

console.log(regexp.test('JavaScript'));
>> true
console.log(regexp.test('I am studying TypeScript'));
>> true
console.log(regexp.test('PostScript is difficult'));
>> false

単語の先頭および末尾にマッチする(\b)

メタ文字のひとつである \b は単語の先頭位置および末尾位置にマッチします。

\b

例えば次のようなパターンは work という文字列が単語の先頭にある場合にマッチします。

const regexp = /\bwork/;

work や working にはマッチします。ただし fireworks のように単語の先頭以外にある場合はマッチしません。

work
〇 a working person
✕ worm
✕ Go to see fireworks

\b は単語の先頭だけでなく単語の末尾にもマッチします。例えば次のようなパターンは ing という文字列が単語の末尾にある場合にマッチします。

const regexp = /ing\b/;

swimming や working にはマッチします。ただし ingenious のように単語の末尾以外にある場合はマッチしません。

〇 swimming
〇 a working person
✕ worm
✕ ingenious design

\b を単語の先頭と末尾にそれぞれ使用した次のようなパターンは working という単語の場合だけにマッチします。前後に文字が付いている場合はマッチしません。

const regexp = /\bworking\b/;
サンプルコード

簡単なサンプルで試してみます。

let regexp1 = /\bwork/;

console.log(regexp1.test('a working person'));
>> true
console.log(regexp1.test('Go to see fireworks'));
>> false

let regexp2 = /ing\b/;

console.log(regexp2.test('a working person'));
>> true
console.log(regexp2.test('ingenious design'));
>> false

単語の先頭と末尾以外にマッチする(\B)

メタ文字のひとつである \B は単語の先頭と末尾以外の位置にマッチします。

\B

例えば次のようなパターンは単語の先頭以外の位置から始まり、そのあとに am と続く場合にマッチします。

const regexp = /\Bam/;

sample や program にはマッチします。ただし amount のように単語の先頭から始まっている場合はマッチしません。

〇 sample
〇 Difficult program
✕ full amount

例えば次のようなパターンは am という文字列のあとが単語の末尾以外の位置だった場合にマッチします。

const regexp = /am\B/;

sample や amount にはマッチします。ただし program のように am が単語の末尾にある場合はマッチしません。

〇 sample
〇 full amount
✕ Difficult program
サンプルコード

簡単なサンプルで試してみます。

let regexp1 = /\Bam/;

console.log(regexp1.test('Difficult program'));
>> true
console.log(regexp1.test('full amount'));
>> false

let regexp2 = /am\B/;

console.log(regexp2.test('full amount'));
>> true
console.log(regexp2.test('Difficult program'));
>> false

-- --

JavaScript の正規表現で文字列の先頭や末尾など位置にマッチするパターンの記述方法について解説しました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。