ruby · onigmo · =~ · gsub · local

Generate Ruby code from a regex

Drop a pattern in, pick flags, and get a Ruby snippet — match, scan, gsub, split — with both the /.../ literal and Regexp.new constructor forms.

Regex → Ruby
//g
Ruby
input = "Reach alice@example.com or bob@test.org."
re = /\\b\\w+@\\w+\\.\\w+\\b/
re_alt = Regexp.new("\\\\b\\\\w+@\\\\w+\\\\.\\\\w+\\\\b")

is_match = !!(input =~ re)
first = input.match(re)
all = input.scan(re)
replaced = input.gsub(re, "[email]")
parts = input.split(re)

puts({
  is_match: is_match,
  first: first && first[0],
  all: all,
  replaced: replaced,
  parts: parts,
}.inspect)
Quick Start

How to use a regex in Ruby

Ruby uses the Onigmo engine and exposes regex as a first-class literal: /pattern/imx. The =~ operator returns the match index or nil.

  1. 01

    Type a pattern

    Slashes inside the pattern are auto-escaped. The output includes both the /…/ literal and a Regexp.new(...) constructor form for dynamic patterns.

    Patterns are parsed with the JavaScript RegExp constructor, so syntax errors surface immediately and engine quirks like Unicode property escapes (\p{L}) require the u flag.

    patternECMAScriptliteralregex
    input · literalpattern · regex
    /\b\w+@\w+\b/
    loaded · ECMAScripttarget · ready
  2. 02

    Tune flags

    JS i/m/x map to /pat/i, /pat/m, /pat/x. Note that Ruby's m flag is JS's s — it makes . match newlines. Ruby has no equivalent to JS m.

    Each flag character mirrors the ECMAScript literal: g enables iteration, i folds case, m anchors per line, s lets . match newlines, u unlocks proper Unicode, y is sticky, and d emits indices.

    flagssampleg · i · mlive
    config · optionsflags · flags
    /pat/im
    flags applied · livelive · preview
  3. 03

    Read the snippet

    Includes =~ (boolean-ish), match (first), scan (all), gsub (replace), and split — printed as an inspectable hash.

    The generator rewrites the regex for the target language — handling string-literal escaping, raw-string prefixes, and engine-specific syntax tweaks.

    codegentargetsnippetcopy
    run · outputpreview · code
    input.scan(re)
    snippet · livecode · ready
  4. 04

    Copy code

    One click copies the full snippet — paste into a .rb file, an irb session, or a Rails console.

    Copy writes via navigator.clipboard.writeText, so nothing transits the network and the output is byte-identical to what you see on screen.

    copyexportclipboardblob
    export · exportedready · saved
    Copied
    ready to shipsuccess
Pro tips

Regex patterns that don't melt down

Use named groups

(?<year>\d{4}) reads better than $1 and survives reordering. Supported in ECMAScript 2018+.

Anchor strictly

Use ^/$ with the m flag when matching whole lines. Without anchors, partial matches sneak through.

Avoid catastrophic backtracking

Nested quantifiers like (a+)+ can explode. Run patterns through ReDoS Detector first.

Escape every literal

Backslash any meta character you want literally: \.\$\^\*\+\?\(\)\[\]\{\}\|\\.

Test edge cases

Empty string, single character, unicode, the maximum length you expect — write fixtures for each.

Patterns aren&rsquo;t parsers

Don’t parse HTML, JSON, or balanced parens with regex. Use a proper parser when the grammar is recursive.

Use Cases

When to generate Ruby regex code

Skip the boilerplate when wiring a pattern into a Rails app, a Jekyll plugin, or a sysadmin script.

Rails validation

Drop a regex into a model with validates :field, format: { with: re }. Compiles through the JavaScript RegExp constructor — engine quirks (Unicode property escapes, sticky matching, named groups) work when their flags are on. Error messages cite the exact position of any syntax issue.

ReDoS-safe

ERB / Liquid filtering

Use gsub in template helpers to sanitise output. Pairs with the ReDoS detector to catch catastrophic backtracking before you deploy. A pattern that handles 1k-character input fine can become a denial-of-service vector on attacker-controlled 1M-character input.

ECMA-compliant

Migrations

Run scan/gsub during a rake task to clean up legacy data. Output exports as JavaScript, Python re, Java util.regex, .NET System.Text.RegularExpressions, PCRE, and POSIX — language quirks are highlighted on conversion so you don't ship a JS-only pattern to a Go service.

spec-grade

Sysadmin scripts

Pipe log files into Ruby one-liners that match and aggregate. Capture groups (named or numbered) round-trip cleanly into replacement strings, JSON output, or CSV extraction without re-typing. Backreferences ($1, ${name}) preserve semantics across languages.

cross-engine

API normalisation

Pre-validate input shape in a Sinatra/Rack middleware. Test against edge cases — empty input, single character, max length, multibyte boundaries — to catch off-by-one and zero-length match bugs before they reach production.

test-ready

Cap deploy hooks

Parse Capistrano output with regex in deploy callbacks. All matching runs client-side so secret patterns never leave the browser. Useful when the pattern itself is sensitive (PII regexes, internal data formats, security filters).

production-ready
FAQ

Frequently asked questions

It matches a regex against a string and returns the index of the first match, or nil. Use !! to convert to boolean (as the snippet does for is_match).
match returns a MatchData object for the first match (or nil). scan returns an array of every match — strings if there are no groups, arrays-of-strings if there are. Use scan when you want them all.
JS m enables ^/$ per line. Ruby's m enables . to match newlines — that's JS's s flag. There's no per-line mode in Ruby (it's the default for ^/$). Easy to mix up.
After a match, m[:name] or m['name'] returns the group's value. The pattern syntax is (?<name>...) just like JS.
No. The code is generated entirely in your browser.
Suggest a tool

Something missing?

Tell us what you need. We ship the top requests every two weeks.

Sent straight to the maintainers · no account needed
47 in queue·8 shipped this month
Request queued. Thanks!