JavaScript 正規表現 マッチ場所の指定

^ 文字列 (または行) の先頭

^は「文字列の先頭」を意味します。

const r = /^abc/
console.log(r.test('Xabcd')) // false
console.log(r.test('abcdX')) // true

m フラグが指定されているときは、「行の先頭」を意味します。

const s = `Hello
abc
Bye`
const r1 = /^abc/
const r2 = /^abc/m
console.log(r1.test(s)) // false
console.log(r2.test(s)) // true

$ 文字列 (または行) の末尾

$は「文字列の末尾」を意味します。

const r = /abc$/
console.log(r.test('Xabc')) // true
console.log(r.test('abcX')) // false

m フラグが指定されているときは、「行の末尾」を意味します。

const s = `Hello
test abc
Bye`
const r1 = /abc$/
const r2 = /abc$/m
console.log(r1.test(s)) // false
console.log(r2.test(s)) // true

\b 文字の境界

\b は「文字の境界」 (boundary) を意味します。 区切りとは、「文字列の先頭」、「文字列の末尾」の他に、「英数字 ([a-zA-Z0-9] または \w) とそれ以外の文字の境界」です。

const r = /\bapple\b/
console.log(r.test('apple orange')) // true
console.log(r.test('orange apple banana')) // true
console.log(r.test('oranges apples')) // false
console.log(r.test('hello apple!')) // true

上の例で apple! の部分は、 !\w に含まれないため、 apple! の間に境界があると考えます。

\B 文字の境界ではない箇所

\B は「文字の境界ではない箇所」を意味します。

const r = /\Bapple\B/
console.log(r.test('apple orange')) // false
console.log(r.test('xxappleb')) // true

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 JavaScript 入門