LoginSignup
10
3

More than 5 years have passed since last update.

ES2018の正規表現の新機能を試してみた

Last updated at Posted at 2019-02-17

参考

↑の内容を元に試しただけという内容ですので、正しい情報が欲しい方は参考ページを見て、本記事は見なくても良いです。
自分の備忘録として投稿させていただきました。
間違っている箇所などあれば、コメントなどよろしくお願いいたします :bow:


tl;dr

以下の機能が追加されるようなので試します

  • s (dotAll) flag for regular expressions
  • RegExp named capture groups
  • RegExp Lookbehind Assertions
  • RegExp Unicode Property Escapes

ちなみにすでにchromeでは動くので、babelなどを使わずそのまま実行していきます。

※2019/2/17現在

image.png

s (dotAll) flag for regular expressions

オプション無しのデフォルトでは、. (ドット)は改行文字にはマッチしないのですが、s オプションをつけることで改行にもマッチします

// sオプション無し -> false
/foo.bar/.test(`foo
bar`)

// sオプション有り -> true
/foo.bar/s.test(`foo
bar`)

Screen Shot 2019-02-17 at 23.18.56.png

RegExp named capture groups

マッチした文字列を連想配列みたいな感じで取れる。

const { year, month, day } = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/.exec('2020-03-04').groups
console.log(year, month, day) // 2020 03 04

↓のように groupsから値を受け取れます。

image.png

\kで使いまわすこともできる!

const re = /(?<dup>ABC)x+\k<dup>/.test('ABCxxxABC'); // true

image.png

replaceでも使うことができる!

console.log('War & Peace'.replace(/(War) & (Peace)/, '$2 & $1'));  // Peace & War 
console.log('War & Peace'.replace(/(?<War>War) & (?<Peace>Peace)/, '$<Peace> & $<War>'));  // Peace & War

// 関数だとこうなる
const result = 'War & Peace'.replace(/(?<War>War) & (?<Peace>Peace)/, function(match, group1, group2, offset, string) {
    return group2 + ' & ' + group1;
});
console.log(result);    // Peace & War

image.png

RegExp Lookbehind Assertions

今まで先読みしかできなかったのですが、後読みの機能が追加されたようです。

console.log(/(?<=a)b/.test('ab')) // true
console.log(/(?<!a)b/.test('cb')) // true

image.png

以下のページも参考

情報ありがとうございます:bow:

RegExp Unicode Property Escapes

以下のページのreadmeを参考にしつついくつかサンプルを試してみました

Number以外にもありますが、一番手軽に試せたのでNumberで確認しました。

// 半角の1
console.log(/\p{Number}/u.test(1)); // true

// 全角の1
console.log(/\p{Number}/u.test('')); // true

// ローマ数字などの10進以外の記号を含む、Unicodeの任意の数字記号と一致
console.log(/^\p{Number}+$/u.test('²³¹¼½¾𝟏𝟐𝟑𝟜𝟝𝟞𝟩𝟪𝟫𝟬𝟭𝟮𝟯𝟺𝟻𝟼㉛㉜㉝ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ')); // true

\p\Pとすると否定になるようです。

image.png


最後まで読んでいただきありがとうございましたm(_ _)m

10
3
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
10
3