LoginSignup
0
0

More than 3 years have passed since last update.

正規表現入門 第三回 数量詞を用いた検索

Last updated at Posted at 2020-08-09

数量詞とは

  • 「数量を示す単語または句」のことを言う。
  • メタ文字と同様、数量詞もそのものを検索する場合はエスケープが必要です。

先頭の文字を検索 "^"

  • 文字列の「先頭」を検索するには「^」を使います。
  • mオプションを加えると、改行直後の値も対象になります。
3-1(先頭の文字を検索).js
console.log("This is a pen!".match(/^This/));
console.log("This is a pen!".match(/^is/));

console.log("This is a pen!\nThis is a ball!".match(/^This/g));
console.log("This is a pen!\nThis is a ball!".match(/^This/gm));

console.log("This is a pen!".match(/^This\s../));
console.log("This is a pen.This is a ball.".replace(/^This/, "That"));

実行結果
[ 'This', index: 0, input: 'This is a pen!', groups: undefined ]
null
[ 'This' ]
[ 'This', 'This' ]
[ 'This is', index: 0, input: 'This is a pen!', groups: undefined ]
That is a pen.This is a ball.

末尾を検索 "$"

  • 文字列の「末尾」を検索するには「$」を使います。
3-2(末尾を検索).js
console.log("This is a pen!".match(/pen!$/));
console.log("This is a pen!".match(/is$/));

console.log("This is a pen!\nThis is a ball!".match(/!$/g));
console.log("This is a pen!\nThis is a ball!".match(/!$/gm));

console.log("This is a pen!".match(/\spen!$/));

console.log("This is a pen.This is a pen.".replace(/pen.$/, "ball."));

実行結果
[ 'pen!', index: 10, input: 'This is a pen!', groups: undefined ]
null
[ '!' ]
[ '!', '!' ]
[ ' pen!', index: 9, input: 'This is a pen!', groups: undefined ]
This is a pen.This is a ball.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0