0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Powerful regexes with XRegExp and tagged template literals

Posted at

TL;DR

Wrapper for XRegExp for seamless and painless usage in modern JavaScript.

$ yarn add xre

GitHub | npm

Why?

XRegExp is the really powerful library, which drastically extends native JS RegExp syntax with tons of wonderful features. But it doesn't provide template literal tag, so developers have to double-escape characters ([\\s\\S]) or use some inelegant ways to avoid escaping (XRegExp(String.raw`[\s\S]`)). Also, developers have to call some methods not as a regexp instance's methods, but as XRegExp's static methods, passing regexp to them (XRegExp.exec('“Word”', XRegExp('(?<word>\w+)')) instead of XRegExp('(?<word>\w+)').exec('“Word”')).

Examples

Install

$ yarn add xre # yarn
$ npm install xre # npm@5
$ npm install xre --save # older npm versions

Simple example

Named groups, free-spacing, comments.

import xre from 'xre';

const date = xre`/
    (?<year>  \d{4}) - # Year
    (?<month> \d{2}) - # Month
    (?<day>   \d{2})   # Day
/x`;

const { year, month, day } = date.exec('2017-06-11');

console.log(`Year: ${year}, month: ${month}, day: ${day}`);
// → Year: 2017, month: 06, day: 11

Yet another simple example

Named groups, Unicode support.

import xre, { configure } from 'xre';
import XRegExp from 'xregexp';

// By default xre uses minimal version of XRegExp
// (to reduce bundle size and loading time),
// so to use the power add-ons we have to configure it
// with the full version of XRegExp.
// If you need to use full version of XRegExp,
// you should configure xre only once in the project,
// Probably, in the entry point.
configure({ XRegExp });

const fullName = xre`/(?<firstName>\p{Letter}+)[\s・](?<lastName>\p{Letter}+)/`;

console.log(fullName.exec('Yuri Gagarin').firstName);
// → Yuri

console.log(fullName.exec('Юрий Гагарин').firstName);
// → Юрий

console.log(fullName.exec('ユーリイ・ガガーリン').firstName);
// → ユーリイ

console.log(fullName.exec('ユーリイ ガガーリン').lastName);
// → ガガーリン

Syntax

xre supports XRegExp literals in two different formats:

const withDefaultFlags = xre`regexp`;
const withCustomFlags = xre`/regexp/flags`;

Default flags are msux.

API

xre instances supports all native RegExp API, so it can be used as an argument for functions and methods like String.prototype.replace or String.prototype.match.

Additionally, it exposes some XRegExp methods, which takes a RegExp as an argument (obviously, this used as such argument when calling them).

Native methods, which supports non-default behavior:

  • exec() — doesn't break default behavior, but can take additional arguments and returns an object with additional fields.
  • test() — doesn't break default behavior, but can take additional arguments.

Non-standard methods:

  • addToken — useful when writing XRegExp add-ons.
  • forEach.
  • globalize.
  • match.
  • replace.
  • split.

Bonus: Highlight xre regexes in IntelliJ IDEA

  1. Download the gist.
  2. Extract files, if you downloaded zipball.
  3. Go to IntelliJ IDEA settings Editor → Language Injections.
  4. Click Import icon on the toolbar on the right side.
  5. Select xre-slashes.xml, then click OK.
  6. Then, import xre.xml.

Now IDEA treats xre regexes as regular expressions and even provides RegExp-specific intentions.

NB: If you edit RegExp in Check RegExp pop-up, IDEA removes slashes around it and flags.

xre regexes highlighting in IntelliJ IDEA

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?