先頭や末尾にマッチするパターン
【開発環境】
OS:Win11(64ビット)
VSCode1.72.2、
クロム
【文字列の先頭にマッチする(^)】
メタ文字のひとつであるキャレット(^)は文字列の先頭位置にマッチします。
・サンプル
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
【文字列の末尾にマッチする($)】
メタ文字のひとつであるドル記号($)は文字列の末尾位置にマッチします。
サンプル
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 は単語の先頭位置および末尾位置にマッチします。
・サンプル
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 は単語の先頭と末尾以外の位置にマッチします。
サンプル
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