LoginSignup
0
0

More than 3 years have passed since last update.

正規表現入門 第一回 オプション

Last updated at Posted at 2020-07-19

学習する契機

  1. 正規表現が苦手で、何かある都度、Google検索してサンプルをコピーして使用している自分が嫌になった。
  2. 本記事では第一弾として、正規表現のオプションについて記載する

正規表現とは

  • 一言で言うならば、「文字列をパターンで表すルール」です。

オプション

  • JavaScriptでは、以下の検索オプションが利用可能です。
オプション 意味
g グロバール検索
i 大文字と小文字を区別しない検索
m 複数行検索
y 特定の位置からの検索

オプションの使用例

  1. オプション指定なし
  2. gオプション指定
  3. iオプション指定
  4. mオプション指定
  5. yオプション指定
  6. オプションの複数指定
1-2(オプション指定なし).js
console.log('ABC_ABC_ABC'.match(/ABC/));

実行結果
[ 'ABC', index: 0, input: 'ABC_ABC_ABC', groups: undefined ]

1-2(gオプション指定).js
console.log('ABC_ABC_ABC'.match(/ABC/g));

実行結果
[ 'ABC', 'ABC', 'ABC' ]

1-2(iオプション).js
console.log('ABC'.match(/abc/));
console.log('ABC'.match(/abc/i));

実行結果
null
[ 'ABC', index: 0, input: 'ABC', groups: undefined ]

1-2(mオプション).js
console.log("ABC\nDEF".match(/^D/));
console.log("ABC\nDEF".match(/^D/m));

実行結果
null
[ 'D', index: 4, input: 'ABC\nDEF', groups: undefined ]

1-2(yオプション).js
var exp = /ABC/y;
console.log(exp.lastIndex);
console.log(exp.test('ABC'));

exp.lastIndex = 1;
console.log(exp.test('ABC'));
console.log('ABC'.match(exp));

実行結果
0
true
false
[ 'ABC', index: 0, input: 'ABC', groups: undefined ]
yオプションを指定すると、検索を任意の位置から始めることが出来ます。
なお、検索位置はRegExpオブジェクトのlastIndexプロパティで指定します。
例を見てわかる通り、yオプションはStringオブジェクトのメソッドでは有効にならない点に注意してくだ
さい。

1-2(gオプションとiオプションの組み合わせ).js
console.log('ABC_abc_ABC'.match(/ABC/gi));

実行結果
[ 'ABC', 'abc', 'ABC' ]

参考URL

次回予告

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