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?

全エントリにライブテスター付きの正規表現チートシートを作った

0
Posted at

作ったもの

Regex Cheatsheethttps://sen.ltd/portfolio/regex-cheatsheet/

スクリーンショット

  • 9 カテゴリに 45 個の構文エントリ
  • 20 個の実用パターン(メール / URL / 電話番号 / UUID / IPv4 / hex color など)
  • 全エントリにライブテスター(パターンとテスト文字列を編集可能)
  • マッチのハイライト + 件数表示
  • ワンクリックコピー

vanilla JS、ゼロ依存、ビルド不要node --test で 47 ケース。

safeCompile で落ちないように

ユーザ入力の正規表現は不正な可能性がある。new RegExp() を try/catch でラップして、エラーメッセージを返す:

export function safeCompile(pattern, flags) {
  try { return { regex: new RegExp(pattern, flags), error: null }; }
  catch (e) { return { regex: null, error: e.message }; }
}

ゼロ幅マッチの無限ループ回避

g フラグで exec を繰り返すとき、^\b のようなゼロ幅マッチは lastIndex を進めない。手動でインクリメントしないと無限ループ:

if (m[0].length === 0) r.lastIndex++;

ハイライトはセグメント分割

テキストを「マッチ / 非マッチ」の交互セグメントに分割し、それぞれを span でレンダリング。HTML エスケープもセグメント単位で処理できるのでシンプル。

シリーズ

100+ 公開ポートフォリオ シリーズの #48 です。

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?